2

我想在单个 foreach 循环中扩展两个数组,例如 ..

$array=array(1,2,3,4,5,6,7,);
$array2=array(1=>'b','2=>c',3=>'d',4=>'e',5=>'f',6=>'g',7=>'x');

foreach($array as first && $aaray2 as second){
  echo first;
  echo second;    
}

可能吗?我如何调用每个数组的索引和每个数组的值

4

6 回答 6

3

Since your arrays don't use named keys you can reuse the array key. If you use named keys this only works if the keys are the same.

foreach ($array as $key => $value) {
    echo $value;
    echo $array2[$key];
}

You could also use a for loop counting from 0 to the array length since php automatically uses numbers as keys if you don't specify any, but the above solution is probably more readable and will work with named keys.

于 2013-09-03T11:24:56.743 回答
2

You can use array_combine to create one array with key=>value pairs.

foreach(array_combine($array, $array2) as $key => $value){

    echo $key;
    echo $value;

}

(array_combine returns the combined array, FALSE if the number of elements for each array isn't equal)

于 2013-09-03T11:25:57.620 回答
0

前几天我写了一个ZipIterator专门用来做这个的类。

使用示例:

$array=array(1,2,3,4,5,6,7,);
$array2=array('b','c','d','e','f','g','x');

foreach (new ZipIterator($array, $array2) as $pair) {
    echo "first: ".$pair[0].", second: ".$pair[1];
}

特征:

  • 适用于所有类型的可遍历对象,而不仅仅是数组
  • 适用于任意数量的可遍历(不一定是两个)
  • 对可遍历对象中包含的值没有任何限制
  • 可以配置为在 shortes 可遍历序列结束时停止(默认行为),或者继续运行直到所有这些都用尽

要求:

  • PHP 5.4 或更高版本

查看它的实际效果并从 GitHub获取源代码。

于 2013-09-03T11:34:30.553 回答
0

您可以像这样使用两个 for 循环:

foreach($array as $arr) {
        echo $arr;
        for($i=1; $i<count($array2); $i++){
            echo $array2[$i];
        }
}
于 2013-09-03T11:28:33.523 回答
0
$array=array(1,2,3,4,5,6,7,);
$array2=array('b','c','d','e','f','g','x');

$mi = new MultipleIterator(
    MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_ASSOC
);
$mi->attachIterator(new ArrayIterator($array), 'val');
$mi->attachIterator(new ArrayIterator($array2), 'val2');
foreach($mi as $details) {
    echo $details['val'], ' - ', $details['val2'], PHP_EOL;
}

或者

$array=array(1,2,3,4,5,6,7,);
$array2=array('b','c','d','e','f','g','x');

$mi = new MultipleIterator(
    MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_ASSOC
);
$mi->attachIterator(new ArrayIterator($array), 'val');
$mi->attachIterator(new ArrayIterator($array2), 'val2');
foreach($mi as $details) {
    extract($details);
    echo $val, ' - ', $val2, PHP_EOL;
}

或仅适用于 PHP 5.5+

$array=array(1,2,3,4,5,6,7,);
$array2=array('b','c','d','e','f','g','x');

$mi = new MultipleIterator(
    MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_ASSOC
);
$mi->attachIterator(new ArrayIterator($array));
$mi->attachIterator(new ArrayIterator($array2));
foreach($mi as list($val, $val2)) {
    echo $val, ' - ', $val2, PHP_EOL;
}
于 2013-09-03T11:44:20.637 回答
-1

只需合并两个数组并循环

$array=array(1,2,3,4,5,6,7,);
$array2=array('b','c','d','e','f','g','x');

$array = array_merge($array, $array2);

foreach ($array as $value) {
    echo $value;
}
于 2013-09-03T11:28:33.057 回答