A recursive method to traverse a multi-dimensional array in PHP
I need a method to traverse a multidimensional array in PHP without using function calls itself.
Basically I have an array like this:
$data = array(
'hoge' => 123,
'foo' => 开发者_运维技巧456,
'bar' => 789,
'aaa' => array(
'abc' => 111,
'bcd' => 222,
'cde' => 333
),
'bbb' => array(
'def' => array(
'efg' => 'hoge'
)
),
'stacks' => array(
'a',
'b'=> array('qwe' => 111,
'asd' => 222,
'args' => array('1',
'2',
'3')),
'c'
)
);
Generally you use a function like this:
function get_array_elems($arrResult, $where="array"){
while(list($key,$value)=each($arrResult)){
if (is_array($value)){
get_array_elems($value, $where."[$key]");
}
} else {
...anything
}
}
get_array_elems($arrResult);
I can not use this method because i have to write this method in a PHP function and it can not write a function in another function.
Can it be done using an iterative method such as while, foreach, array_walk_recursive etc.?
array_walk_recursive
will still work. Just use an anonymous function: http://php.net/manual/en/functions.anonymous.php as the callback. You can use anonymous functions inside other functions so it should work for you. Just make sure you are using at least PHP 5.3.0 since thats when anonymous functions were introduced.
Although I also cannot see how using a recursive function would be impossible, but as a programming excercise it is an interesting one.
If you were to mimic recursion, you should keep your own stack to keep track of your position in every level, but that's a real PITA, so if it's all the same you'd better first go through level 0, 1, 2 etc in that order and collect nested arrays as you go. E.g.:
function walk($walk)
{
while ( count($walk) > 0 )
{
$defer = array();
foreach ( $walk as $k=>$v )
{
if ( is_array($v) )
{
foreach ( $v as $kk=>$vv ) $defer["$k.$kk"] = $vv;
} else {
print "$k=>$v\n";
}
}
$walk = $defer;
}
}
but this obviously has different characteristics than the typical recursion solution, which may or may not be a problem.
精彩评论