php 你如何将两个 foreach 循环合二为一

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

How do you combine two foreach loops into one

phpforeach

提问by Kirk

The language is PHP. I have one foreach ( $a as $b) and another foreach ($c as $d => $e). How do i combine them to read as one. I tired foreach (($a as $b) && ($c as $d => $e)), but that is rubbish.

语言是 PHP。我有一个 foreach($a 作为 $b)和另一个 foreach($c 作为 $d => $e)。我如何将它们结合起来阅读。我厌倦了 foreach (($a as $b) && ($c as $d => $e)),但那是垃圾。

回答by VolkerK

You might be interested in SPL's MultipleIterator

您可能对SPL 的 MultipleIterator感兴趣

e.g.

例如

// ArrayIterator is just an example, could be any Iterator.
$a1 = new ArrayIterator(array(1, 2, 3, 4, 5, 6));
$a2 = new ArrayIterator(array(11, 12, 13, 14, 15, 16));

$it = new MultipleIterator;
$it->attachIterator($a1);
$it->attachIterator($a2);

foreach($it as $e) {
  echo $e[0], ' | ', $e[1], "\n";
}

prints

印刷

1 | 11
2 | 12
3 | 13
4 | 14
5 | 15
6 | 16

回答by T.Todua

1) First method

1)第一种方法

<?php
$FirstArray = array('a', 'b', 'c', 'd');
$SecondArray = array('1', '2', '3', '4');

foreach(array_combine($FirstArray, $SecondArray) as $f => $n) {
    echo $f.$n;
    echo "<br/>";
}
?>

or 2) Second method

或 2) 第二种方法

<?php
$FirstArray = array('a', 'b', 'c', 'd');
$SecondArray = array('1', '2', '3', '4');

for ($index = 0 ; $index < count($FirstArray); $index ++) {
  echo $FirstArray[$index] . $SecondArray[$index];
  echo "<br/>";
}
?>

回答by cletus

I don't understand what you're trying to do. If you want to reach them one after the other just use two loops:

我不明白你想做什么。如果您想一个接一个地到达它们,只需使用两个循环:

foreach ($a as $b) { ... }
foreach ($c as $d => $e) { ... }

If you want all combinations from $aand $c:

如果您想要来自$a和的所有组合$c

foreach ($a as $b) {
  foreach ($c as $d => $e) {
    // do stuff
  }
}

I guess you could do something like:

我想你可以这样做:

foreach (array_merge($a, $c) as $k => $v) {
  ...
}

but I wouldn't necessarily advise it.

但我不一定会建议它。

回答by zombat

This will do what you want I think. It will be advance both arrays equally at the same time throughout your loop. You can always breakmanually if $cis a different size than $aand you need breaking logic based on array size:

这会做你想做的我认为。它将在整个循环中同时平等地推进两个数组。break如果$c大小$a与数组大小不同,并且需要根据数组大小破坏逻辑,则始终可以手动进行:

foreach($a as $b)
{
    list($d,$e) = each($c);
    //continue on with $b, $d and $e all set
}

each()will advance the array pointer of $con each iteration.

each()$c在每次迭代中推进数组指针。