Tuesday, December 7, 2010

find path of a key in a multi-dimensional tree-like array

Programmer Question

hey, I have this array (the actual array can be several level deeps and spans a tree-structure)



array
3 =>
array
4 =>
array
7 => null
8 => null
5 => null
6 => null


Now, e.g. I want the path to key 7, it can be shown like this:



array
0 => int 7
1 => int 4
2 => int 3


Can someone help me with such a recursion function?
I am able to get:



array
0 => int 7
1 => int 4


using:



function tree_path($key,$tree,&$path=null) {
if(!is_array($path)) $path = array();
if(is_array($tree)) {
if (!array_key_exists($key,$tree)) {
foreach ($tree as $id=>$child) {
$found = tree_path($key,$child,$path);
if($found) $path[] = $id;
}
} else {$path[] = $key; return true; }
}
}


Oh. I recently saw the use of passing-by-reference in foreach loop. Can something like that be added here?



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails