我有这个任意的多维数组。
Array (
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[5] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[10] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[15] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[1] => Array
(
[0] => 2
[1] => 1
[2] => 2
)
[2] => Array
(
[0] => 2
[1] => 1
[2] => 2
)
)
我想运行for循环来提取每个子数组的数据。 但我不能做一个简单的for循环,因为索引(0,5,10,15,1)是任意的。 有没有办法运行for循环然后跳过子数组,如果它是空的?
谢谢!
答案 0 :(得分:3)
这将采用$array
并循环通过它,回显键
你有一个数组中的数组,你可以在foreach中放置一个foreach:
// First we take the main array ($array) and loop though its values
foreach( $array as $main_key =>$sub_array){
echo $main_key.": <br />\n"; // echo the key, some extra html to format
// the values of the mainarray are arrays themselves, just loop again:
foreach($subarray as $sub_key =>$subvalue){
echo '- '.$subvalue."<br />\n";
}
}
如果你在foreach中预告,这里有一点陷阱:
foreach($array as $key =>$value){
foreach($value as $key=>$value){ /* ... */; }
}
这将产生非常奇怪的结果。内部foreach使用相同的参数名称,并且会搞砸所有内容。