Is there a way to loop through a multidimensional array without knowing it's depth?

后端 未结 5 1764
滥情空心
滥情空心 2020-12-01 16:39

So far, if I have to loop through a multidimensional array, I use a foreach loop for each dimension.

e.g for two dimensions

foreach($array as $key=&g         


        
5条回答
  •  囚心锁ツ
    2020-12-01 17:07

    Simple function inside array_walk_recursive to show the level of nesting and the keys and values:

    array_walk_recursive($array, function($v, $k) {
                                     static $l = 0;
                                     echo "Level " . $l++ . ": $k => $v\n";
                                 });
    

    Another one showing use with a reference to get a result:

    array_walk_recursive($array, function($v) use(&$result) {
                                     $result[] = $v;
                                 });
    

提交回复
热议问题