php 在 foreach 里面放一个 foreach
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9132532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
putting a foreach inside foreach
提问by nobito
I'm trying to loop some array using foreach
.
This is the code which demonstrates what I'm doing:
我正在尝试使用foreach
. 这是演示我在做什么的代码:
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
foreach($arr1 as $key => $val){
foreach($arr2 as $key2 =>$val2){
echo $val."-".$key2."-".$val2;
}
}
However, this outputs
然而,这输出
32-0-5
32-1-3
32-2-2
32-3-1
32-0-5
32-1-3
32-2-2
32-3-1
and I want to display it like this instead
我想像这样显示它
32-1-5
45-2-3
67-3-2
89-3-1
32-1-5
45-2-3
67-3-2
89-3-1
How can I solve this? Since I'm a beginner I don't know what to do.
我该如何解决这个问题?由于我是初学者,我不知道该怎么做。
回答by Rocket Hazmat
You don't want to loop over the 2nd array, you just want to get the value at a certain position. Try it like this:
您不想遍历第二个数组,只想获取某个位置的值。像这样尝试:
foreach($arr1 as $key => $val){
$val2 = $arr2[$key];
echo $val."-".($key+1)."-".$val2;
}
回答by ElementalStorm
I assume you're doing a double foreach because you actually want to print 4*4 = 16 rows. I also assume that you mistyped the last row, where you have a 3 instead of a 4.
我假设您正在执行双重 foreach,因为您实际上想要打印 4*4 = 16 行。我还假设您输错了最后一行,那里是 3 而不是 4。
Just using ($key2+1) can be enough for you ?
只使用 ($key2+1) 对你来说就足够了吗?
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
foreach($arr1 as $key => $val){
foreach($arr2 as $key2 =>$val2){
echo $val."-" . ($key2+1) . "-".$val2;
}
}
回答by ultra
You can use for loop instead of foreach too:
您也可以使用 for 循环而不是 foreach:
$arr1=array(32,45,67,89);
$arr2=array(5,3,2,1);
for ($i = 0; $i < 4; $i++) {
echo $arr1[$i] . "-" . ($i+1) . "-" . $arr2[$i];
}
回答by DonnellC
$i<count ($arr1)
counts the number of elements in the array.
And then stop once it gets to the end.
$i<count ($arr1)
计算数组中元素的数量。然后在结束时停止。
If you have the name number of elements in each array. This would be great for you or even to create tables dynamically.
如果您有每个数组中元素的名称数量。这对您甚至动态创建表都非常有用。
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
for ($i=0; $i<count ($arr1) ; $i++){
echo $arr1[$i] . "-" . $arr1[$i]."-". $arr2[$i] ;
}
回答by Adrian
Do not nest the loops;
不要嵌套循环;
Use one loop and print array1[i]."-".array2[i]
使用一个循环并打印 array1[i]."-".array2[i]