php 如何同时遍历两个数组而不重新遍历父循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15487386/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:19:44  来源:igfitidea点击:

How can I iterate through two arrays at the same time without re-iterating through the parent loop?

php

提问by Rogers

How can I iterate through two arrays at the same time that have equal sizes ?

如何同时迭代具有相同大小的两个数组?

for example , first array $a = array( 1,2,3,4,5);second array $b = array(1,2,3,4,5);

例如,第一个数组$a = array( 1,2,3,4,5);第二个数组$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 />"; 
    }
}

回答by Nick Andriopoulos

Use a normal forloop instead of a foreach, so that you get an explicit loop counter:

使用普通for循环而不是 a foreach,以便获得显式循环计数器:

for($i=0; $i<count($content)-1; $i++) {
  echo $content[$i].'-'.$contentb[$i];
}

If you want to use string based indexed arrays, and know that the string indexes are equal between arrays, you can stick with the foreachconstruct

如果你想使用基于字符串的索引数组,并且知道数组之间的字符串索引是相等的,你可以坚持使用foreach构造

foreach($content as $key=>$item) {
  echo $item.'-'.$contentb[$key];
}

回答by Mark Baker

Not the most efficient, but a demonstration of SPL's multipleIterator

不是最有效的,而是 SPL 的 multipleIterator 的演示

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($a));
$mi->attachIterator(new ArrayIterator($b));

$newArray = array();
foreach ( $mi as $value ) {
    list($value1, $value2) = $value;
    echo $value1 , '-' , $value2 , PHP_EOL;
}

回答by LuaWeaver

If they're the same size, just do this:

如果它们的大小相同,请执行以下操作:

foreach($a as $key => $content){
   $contentb = $b[$key];
   echo($content."-".$contentb."<br />");
}