Re: unset in foreach breaks recrusion

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



That's not the problem. Look that the function is called with &$return, so
there is a reference to the variable in which the function returns the value
(if not there would not be an answer...).

Otherwise, i think the problem is in the recursive call inside the function.
Once you make the unset, you make a recursive call to the function like:

recrusion(&$array, &$return, $id, $level+1);

while I think the problem will be solved if you make the call just like:

recrusion($array, &$return, $id, $level+1);

Notice that the $array variable has not & symbol, so is the variable
itself and not a reference of it.

Although there is a better and simple solution for that problem (or I
think something like this should work well):

<?php
function recrusion($array, $return, $pid=0, $level=0){
	foreach($array as $id=>$parent){
		if( $parent===$pid ){
			$return[$id]= $level;
			unset($array[$id]); /* remove this to get correct results */
			$level++;
                        $pid = $id;
		}
	}
}
$return= array();
$array= array(1=>0,2=>1,3=>2,4=>3,5=>2,6=>2,7=>6,8=>6,9=>0,10=>0);
recrusion($array, &$return);
var_dump( $return );
?>

So you don't make any recursive call, you don't lose too much
efficiency and it should work well for the whole array.

Try the two solutions above and see whether if any is up to your problem.

Cheers,

Roberto



On Mon, Jun 30, 2008 at 14:27, Jason Norwood-Young <
jason@xxxxxxxxxxxxxxxxxxx> wrote:

> On Sun, 2008-06-29 at 18:25 -0800, David Sky wrote:
> > Hello everyone!
> >
> > A couple of days ago I submitted a bug to PHP
> > http://bugs.php.net/bug.php?id=45385
> > But I was mistaken, apparently it's not a bug.
> > And I was "sent" here to get help.
>
> I think you might be forgetting to return $return.
>
> J
>
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux