Run this...:
<?php
function recrusion($array, $return, $pid=0, $level=0)
{
foreach($array as $id=>$parent)
{
if( $parent===$pid )
{
$return[$id]= $level;
/* remove "unset" for correct results */
unset($array[$id]);
recrusion(&$array, &$return, $id, $level+1);
}
}
}
/* input array as id=>parent */
$array= array(1=>0,2=>1,3=>2,4=>3,5=>2,6=>2,7=>6,8=>6,9=>0,10=>0);
$return= array();
recrusion($array, &$return);
/* return array is id=>level */
var_dump( $return );
?>
Expected result:
----------------
array(10) { [1]=> int(0) [2]=> int(1) [3]=> int(2) [4]=> int(3) [5]=>
int(2) [6]=> int(2) [7]=> int(3) [8]=> int(3) [9]=> int(0) [10]=> int(0)
}
Actual result:
--------------
array(6) { [1]=> int(0) [2]=> int(1) [3]=> int(2) [4]=> int(3) [9]=>
int(0) [10]=> int(0) }
The recrusion will stop at the deepest child, removing the "unset()" will allow recrusion to complete. My head can't take it anymore, I tried so many different things, please, if you can, help :)
I'm using unset to fastern future recrusions, as the actual array is much bigger.
Unsetting part of array in loop does not effect the loop. Using reference ($helper= &$array) doesn't help. I think it's possible ro make the depest id as the last one in the list (simple sort), but it won't solve the above "bug"...
David.