PHP: Best way to iterate two parallel arrays?

前端 未结 3 1883
眼角桃花
眼角桃花 2020-12-05 12:24

As seen in this other answer, there are several ways to iterate two same-sized arrays simultaneously; however, all of the methods have a rather significant pitfall. Here ar

相关标签:
3条回答
  • 2020-12-05 12:59

    As of PHP 5.5 you can do this:

    foreach (array_map(null, $array1, $array2) as list($item1, $item2))
    {
        var_dump($item1);
        var_dump($item2);
    }
    

    http://us3.php.net/manual/en/control-structures.foreach.php#control-structures.foreach.list

    0 讨论(0)
  • 2020-12-05 13:01

    You can use a MultipleIterator:

    $iterator = new MultipleIterator;
    $iterator->attachIterator(new ArrayIterator($array1));
    $iterator->attachIterator(new ArrayIterator($array2));
    
    foreach ($iterator as $values) {
        var_dump($values[0], $values[1]);
    }
    

    You can find more examples concerning the various options in the docs.

    0 讨论(0)
  • 2020-12-05 13:01
    <?php
    
    $arr1 = array( 'a' => 1, 'b' => FALSE, 'c' => new DateTime() );
    $arr2 = array( 'foo', TRUE, 7, 5 );
    
    
    reset($arr1);
    reset($arr2);    
    
    while ( (list($key, $val) = each($arr1))
        && (list($key2, $val2) = each($arr2))
    ) {
        var_dump($val,$val2);
        // or whatever you wanted to do with them
    }
    

    http://www.php.net/manual/en/function.each.php

    0 讨论(0)
提交回复
热议问题