在PHP中使用foreach语句进行多数组回显 [英] Multiple array echo with foreach statement in php
本文介绍了在PHP中使用foreach语句进行多数组回显的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
PHP foreach循环中的多个索引变量
我们可以使用单个 foreach
语句回显多个数组吗?
Can we echo multiple arrays using single foreach
statement?
尝试通过以下方式进行操作,但未成功:
Tried doing it in following way but wasn't successful:
foreach($cars, $ages as $value1, $value2)
{
echo $value1.$value2;
}
推荐答案
假定两个数组具有相同数量的元素,这应该可以工作
assuming both arrays have the same amount of elements, this should work
foreach(array_combine($cars, $ages) as $car => $age){
echo $car.$age;
}
如果不能保证数组的长度相同,则可以执行以下操作
if the arrays are not guaranteed to be the same length then you can do something like this
$len = max(count($ages), count($cars));
for($i=0; $i<$len; $i++){
$car = isset($cars[$i]) ? $cars[$i] : '';
$age = isset($ages[$i]) ? $ages[$i] : '';
echo $car.$age;
}
如果您只想加入两个数组,可以这样做
if you just want to join the two arrays, you can do it like this
foreach(array_merge($cars, $ages) as $key => $value){
echo $key . $value;
}
这篇关于在PHP中使用foreach语句进行多数组回显的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文