Re: [PHP] unset in foreach breaks recrusion
- From: lists@xxxxxxxxx (Jim Lucas)
- Date: Tue, 01 Jul 2008 07:34:45 -0700
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.
- Follow-Ups:
- Re: [PHP] unset in foreach breaks recrusion
- From: "David Sky"
- Re: [PHP] unset in foreach breaks recrusion
- References:
- Re: [PHP] unset in foreach breaks recrusion
- From: "David Sky"
- Re: [PHP] unset in foreach breaks recrusion
- Prev by Date: RE: [PHP] can you give me example of website using postgresql database?
- Next by Date: Re: [PHP] Simple array problem
- Previous by thread: Re: [PHP] unset in foreach breaks recrusion
- Next by thread: Re: [PHP] unset in foreach breaks recrusion
- Index(es):
Relevant Pages
|