有没有办法在不知道深度的情况下遍历多维数组? [英] Is there a way to loop through a multidimensional array without knowing it's depth?
问题描述
到目前为止,如果我必须遍历一个多维数组,我会为每个维度使用一个 foreach 循环.
So far, if I have to loop through a multidimensional array, I use a foreach loop for each dimension.
例如二维
foreach($array as $key=>$value)
{
foreach($value as $k2=>$v2)
{
echo
}
}
不知道数组的深度怎么办?即深度是可变的.
What do I do when I don't know the depth of the array? ie the depth is variable.
我唯一能想到的就是编写一整堆循环代码,如果下一个值不是数组就中断循环.这看起来有点傻.
The only thing I can think of is to code a whole stack of loops and to break the loop if the next value is not an array.This seems a little silly.
有更好的方法吗?
推荐答案
是的,您可以使用 递归.这是一个输出数组中所有元素的示例:
Yes, you can use recursion. Here's an example where you output all the elements in an array:
function printAll($a) {
if (!is_array($a)) {
echo $a, ' ';
return;
}
foreach($a as $v) {
printAll($v);
}
}
$array = array('hello',
array('world',
'!',
array('whats'),
'up'),
array('?'));
printAll($array);
在进行递归时,您应该始终记住的是,您需要一个基本情况,这样您就不会再深入了.
What you should always remember when doing recursion is that you need a base case where you won't go any deeper.
我喜欢在继续函数之前检查基本情况.这是一个常见的习语,但不是绝对必要的.如果您应该输出或执行递归调用,您也可以在 foreach
循环中检查,但我经常发现这样的代码更难维护.
I like to check for the base case before continuing the function. That's a common idiom, but is not strictly necessary. You can just as well check in the foreach
loop if you should output or do a recursive call, but I often find the code to be harder to maintain that way.
当前输入与基本情况之间的距离"称为变体,并且是一个整数.在每次递归调用中,变体都应该严格减少.前面例子中的变体是$a 的深度
.如果您不考虑变体,您可能会面临无限递归的风险,最终脚本将因 而死亡堆栈溢出.在递归函数之前准确记录注释中的变体的情况并不少见.
The "distance" between your current input and the base case is called a variant and is an integer. The variant should be strictly decreasing in every recursive call. The variant in the previous example is the depth of $a
. If you don't think about the variant you risk ending up with infinite recursions and eventually the script will die due to a stack overflow. It's not uncommon to document exactly what the variant is in a comment before recursive functions.
这篇关于有没有办法在不知道深度的情况下遍历多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!