简体   繁体   中英

PHP recursively go through array

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');

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM