是否有过不知道它的深度多维数组的方式来循环? [英] 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.
我能想到的唯一的事情是code环的整个堆叠并打破循环,如果下一个值不是一个array.This似乎有点傻。
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
循环,但我经常发现code是难以维持的方式。
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.
您的电流输入和基本情况之间的距离被称为变异并为整数。变体应严格递减在每一个递归调用。在previous例子中的变体是变量$ 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屋!