Re: unset in foreach breaks recrusion

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

 



Jim,

Read the first emails, your idea was my initial design, eg.
$sorted= array();
recrusion($array, &$sorted);
var_dump( $sorted );

It's not a "nice" solution due to a need to create variable before the call.
Using my final function it will return sorted array into new variable eg
$sorted = recur($array);

It's easier to use and understand :)


Thanks for your reply!


On Tue, Jul 1, 2008 at 6:34 AM, Jim Lucas <lists@xxxxxxxxx> wrote:
> David Sky wrote:
>>
>> Hey,
>>
>> Can't use your example, as you check weather
>> $sorted is empty, if it is -> run the foreach and return,
>> but on next recursion when it's not empty - do nothing :)
>>
>> Though I found how to cut a few seconds (on very big array),
>> removing the first if, and adding a $return=true to functions'
>> parameters, and in future calls set it to false:
>>
>> function recur($array, &$sorted=array(), $pid=0, $level=0, $return=true)
>> {
>>                foreach($array as $id=>$parent)
>>                {
>>                        if($pid===$parent)
>>                        {
>>                                $sorted[$id]= $level;
>>                                unset($array[$id]);
>>                                if(in_array($id,$array)){
>>                                        recur($array, &$sorted, $id,
>> $level+1, false);
>>                                }
>>                        }
>>                }
>>                if($return){return $sorted;}
>> }
>>
>>
>> Well, I guess that's it, I'm sure I can think of
>> another way to cut execution time, but, well,
>> I don't have much time for it :)
>>
>
> Why are you returning anything at all?  I mean, you are making your function
> call like this right?
>
> $dataOut = recur($dataIn, array(), 3);
>
> You are passing the second argument as a reference already, why not keep it
> that way at the top level.  Do this instead.
>
> recur($dataIn, $dataOut, 3);
>
>
> Now, from what you function looks like, it would return $sorted through the
> reference $dataOut.
>
> Then you can get rid of the extra if($return){return $sorted;} thing. Remove
> the last argument from the function definition and you should now be a
> little faster also.
>
>>
>> Thanks all!
>>
>> David.
>>
>

-- 
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