0

I have an array looking like this:

$arr = array(
    array(
        'name'  =>  'n1',
        'id'    =>  0,
        'children' =>   array(
                array(
                    'name'  =>  'n2',
                    'id'    =>  1,
                    'children'  =>  array(
                        array(
                            'name'  =>  'n3',
                            'id'    =>  2,
                            'children'  =>  array(),
                        ),
                        array(
                            'name'  =>  'n4',
                            'id'    =>  3,
                            'children'  =>  array(),
                        ),
                    ),
                ),
                array(
                    'name'  =>  'n17',
                    'id'    =>  4,
                    'children'  =>  array(),
                ),
            ),
        ),
    );

but on a bigger scale.

I want to write a php recursive function which receives the id of the searched element as argument and returns the names it went through to get there, for example, for id==4, the result should be:

array('n1', 'n17');

4

1 回答 1

0
function test($arr, $v, &$x){
    if($x==null)$x=array();
    foreach ($arr as $sub){
        if($sub['id']==$v){
            array_push($x,$sub['name']);
            return true;
        }
        if (test($sub['children'],$v,$x)){
            array_unshift($x,$sub['name']);
            return true;
        }
    }
}
test($myArr,4,$result);
print_r($result);
于 2013-08-24T16:31:30.240 回答