这段内容是关于IT技术的,涉及到PHP语言。其中有两个foreach循环,一个是foreach($a as $b),另一个是foreach($c as $d => $e)。请问如何将它们合并成一个循环来读取数据?我尝试使用foreach (($a as $b) && ($c as $d => $e)),但是这种方法行不通。
您可能对SPL的MultipleIterator感兴趣。
例如:
// 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";
}
打印
1 | 11
2 | 12
3 | 13
4 | 14
5 | 15
6 | 16
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/>";
}
?>
或者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/>";
}
?>
foreach ($a as $b) { ... }
foreach ($c as $d => $e) { ... }
$a
和$c
获取所有组合:foreach ($a as $b) {
foreach ($c as $d => $e) {
// do stuff
}
}
foreach (array_merge($a, $c) as $k => $v) {
...
}
但我不一定建议这样做。
我认为这将达到您想要的效果。它将在循环过程中同时等量地提升两个数组。如果您需要基于数组大小进行打破逻辑,并且$c
与$a
的大小不同,则始终可以手动break
:
foreach($a as $b)
{
list($d,$e) = each($c);
//continue on with $b, $d and $e all set
}
each()
函数会在每次迭代时将数组指针向前移动 $c
。