我想在单个 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;
}
可能吗?我如何调用每个数组的索引和每个数组的值
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.
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)
前几天我写了一个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];
}
特征:
要求:
您可以像这样使用两个 for 循环:
foreach($array as $arr) {
echo $arr;
for($i=1; $i<count($array2); $i++){
echo $array2[$i];
}
}
$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;
}
只需合并两个数组并循环
$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;
}