Run this...:

function recrusion($array, $return, $pid=0, $level=0)
	foreach($array as $id=>$parent)
		if( $parent===$pid )
			$return[$id]= $level;
			/* remove "unset" for correct results */
			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"...


10 Years
Discussion Span
Last Post by Spaiz

I need to find the fastest way to sort an array where one value is id and one is a parent_id. The result should be same array but with additional value of depth(level).

See the example in first post, you should understand.

Of course there are other ways to do it, one of them is running the recrusion without unset, but the all much slower then with unset.

I trying to do somesthing similar with while() and next() but almost sure it will be slower.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.