Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_walk_recursive with array?

I have a menu array, it's a multidimensional array, and I want to do some thing with every single item, so I tried array_walk_recursive. Here is the menu:

$menu = array(
    array(
        'name'=>'a',
        'url'=>'b',
    ),
    array(
        'name'=>'c',
        'url'=>'d',
        'children'=>array(
            array(
                'name'=>'e',
                'url'=>'f'
            )
        )
    )
);

But array_walk_recursive only let me handle every single element, but not array.

array_walk_recursive($menu, function(&$item){
    var_dump($item);//return a;b;c;d;e;f;g
});

What I want is like this:

array_walk_recursive_with_array($menu, function(&$item){
    var_dump($item);//return array('name'=>'a','url'=>'b');a;b;array('name'=>'c',...);c;d;...
    if(is_array($item) && isset($item['name'])){
        // I want to do something with the item.
    }
})

Is there any PHP native function implementation?

like image 740
missingcat92 Avatar asked Jul 03 '14 12:07

missingcat92


1 Answers

according to the array_walk_recursive documentation, you can't get the inner array key. One way to perform your need is to use array_walk and creating your own recursivity.

function HandleArray(&$value){
    if(is_array($value)){
        //Do something with all array
        array_walk($value,'HandleArray');
    }
    else{
       //do something with your scalar value
    }
}
array_walk(array($your_array),'HandleArray');
like image 76
artragis Avatar answered Sep 28 '22 03:09

artragis