如何在foreach循环中同时打印两个数组?

时间:2012-10-24 09:58:54

标签: php foreach

  

可能重复:
  Iterate through two associative arrays at the same time in PHP

我有两个数组$name[]$type[]。我想通过这样的foreach循环打印那些arraya,

<?php
foreach($name as $v && $type as $t)
{
echo $v;
echo $t;
}
?>

我知道这是错误的,然后告诉我这样做的正确方法。

4 个答案:

答案 0 :(得分:10)

你不能那样做。您需要执行以下操作之一:

  1. 使用for循环并“共享”索引变量,或
  2. each和朋友手动迭代,或
  3. 将两个数组与array_map
  4. 压缩在一起

    for的示例:

    for ($i = 0; $i < count($name); ++$i) {
        echo $name[$i];
        echo $type[$i];
    }
    

    可能的问题:数组需要进行数字索引,如果它们的长度不同,则使用count的数组很重要。您应该定位较短的数组,也可以采取适当的措施,不要将较长的数组索引到超出界限范围内。

    each的示例:

    reset($name);  // most of the time this is not going to be needed,
    reset($type);  // but let's be technically accurate
    
    while ((list($k1, $n) = each($name)) && (list($k2, $t) = each($type))) {
        echo $n;
        echo $t;
    }
    

    可能的问题:如果数组的长度不同,那么在“较短”的数组耗尽后,这将停止处理元素。您可以通过为||交换&&来更改此设置,但是您必须考虑$n$t中的一个并不总是具有有意义的值。

    array_map的示例:

    // array_map with null as the callback: read the docs, it's documented
    $zipped = array_map(null, $name, $type);
    
    foreach($zipped as $tuple) {
        // here you could do list($n, $t) = $tuple; to get pretty variable names
        echo $tuple[0]; // name
        echo $tuple[1]; // type
    }
    

    可能的问题:如果两个数组的长度不同,那么较短的数组将使用空值进行扩展;你无法控制这一点。此外,虽然方便,但这种方法确实会占用额外的时间和内存。

答案 1 :(得分:1)

如果数组的长度始终相同,并且元素是唯一的,并且$name的所有值都是字符串或整数,则可以使用array_combine

foreach (array_combine($name, $type) as $v => $t) {
    echo $v, $t;
}

array_combine创建一个新数组,第一个数组的元素提供键,而第二个数组的元素提供值。

答案 2 :(得分:0)

您可以在while循环中使用手动数组迭代函数next()reset()current()

reset($a);
reset($b);

while( (next($a) !== false) || (next($b) !== false)){
    $t = current($a);
    $v = current($b);
}

答案 3 :(得分:-1)

你可以这样做

for ($i = 0; $i < max(count($name), count($type)); $i++) { 
    if(isset($name[$i]))
        echo 'name[' . $i . '] = ' . $name[$i];  
    if(isset($type[$i]))
        echo 'type[' . $i . '] = ' . $type[$i]; 
}