PHP:如何使用foreach打印多维数组元素? [英] PHP: How can I print multi-dimensional array elements using foreach?
问题描述
$ shop = array(
array( Rose,1.25,15),
array( Daisy,0.75,25),
array( Orchid,1.15,7)
);
for($ i = 0; $ i< = count($ shop); $ i ++){
foreach($ shop [$ i] as $ key = > $ val)
echo $ key。 ’=’。 $ val。 ’< br>’;
}
这就是我得到的输出:
0 =玫瑰
1 = 1.25
2 = 15
0 =雏菊
1 = 0.75
2 = 25
0 =兰花
1 = 1.15
2 = 7
============================= ==============
但是随后出现错误:
警告:为foreach()提供了无效的参数
我想知道如何纠正此问题,以及是否有更有效的方法
谢谢大家。
问题是,您使用的是< =
而不是<
。因此,您的for循环前进了一步,数组超出了范围。
for($ i = 0; $ i < count($ shop); $ i ++){
foreach($ shop [$ i] as $ key => $ val)
echo $ key。 ’=’。 $ val。 ’< br>’;
}
$shop = array(
array("Rose", 1.25 , 15),
array("Daisy", 0.75 , 25),
array("Orchid", 1.15 , 7)
);
for($i = 0; $i <= count($shop); $i++){
foreach($shop[$i] as $key => $val)
echo $key . ' = ' . $val . '<br>';
}
So this is the output I'm getting:
0 = Rose
1 = 1.25
2 = 15
0 = Daisy
1 = 0.75
2 = 25
0 = Orchid
1 = 1.15
2 = 7
============================================
But then I get an error:
Warning: Invalid argument supplied for foreach()
What I want to know is how to correct this, and if there's a more efficient way to write what I'm trying to output?
Thanks guys.
The problem is, your using <=
instead of <
. So your for loop goes one step to far and the array is out of bounds.
for($i = 0; $i < count($shop); $i++){
foreach($shop[$i] as $key => $val)
echo $key . ' = ' . $val . '<br>';
}
这篇关于PHP:如何使用foreach打印多维数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!