Re: unset in foreach breaks recrusion
| From: | Jim Lucas | Date: | Tue, 01 Jul 2008 14:34:45 +0000 |
| Subject: | Re: unset in foreach breaks recrusion | ||
| References: | 1 2 3 4 5 6 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-276172@lists.php.net to get a copy of this message | ||
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.