如何在不同时迭代父循环的情况下同时迭代两个数组? [英] How can I iterate through two arrays at the same time without re-iterating through the parent loop?
问题描述
如何同时遍历两个大小相等的数组?
How can I iterate through two arrays at the same time that have equal sizes ?
例如,第一个数组$a = array( 1,2,3,4,5);
第二个数组$b = array(1,2,3,4,5);
for example , first array $a = array( 1,2,3,4,5);
second array $b = array(1,2,3,4,5);
我想通过两次迭代来获得的结果是让循环过程经历相同的值以产生类似的结果
The result that I would like through iterating through both is having the looping process going through the same values to produce a result like
1-1
2-2
3-3
4-4
5-5
我在下面尝试过这种方式,但是它没有用,它继续通过第一个循环
I tried to do it this way below but it didn't work , it keeps going through the first loop again
foreach($a as $content) {
foreach($b as $contentb){
echo $a."-".$b."<br />";
}
}
推荐答案
使用普通的for
循环而不是foreach
,以便获得显式的循环计数器:
Use a normal for
loop instead of a foreach
, so that you get an explicit loop counter:
for($i=0; $i<count($content)-1; $i++) {
echo $content[$i].'-'.$contentb[$i];
}
如果要使用基于字符串的索引数组,并且知道数组之间的字符串索引相等,则可以坚持使用foreach
构造
If you want to use string based indexed arrays, and know that the string indexes are equal between arrays, you can stick with the foreach
construct
foreach($content as $key=>$item) {
echo $item.'-'.$contentb[$key];
}
这篇关于如何在不同时迭代父循环的情况下同时迭代两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!