Interleaving multiple arrays into a single array

后端 未结 4 848
孤独总比滥情好
孤独总比滥情好 2020-11-27 22:04

I need to merge several arrays into a single array. The best way to describe what I\'m looking for is \"interleaving\" the arrays into a single array.

For example

相关标签:
4条回答
  • 2020-11-27 22:13

    If the arrays only have numeric keys, here's a simple solution:

    $longest = max( count($arr1), count($arr2) );
    $final = array();
    
    for ( $i = 0; $i < $longest; $i++ )
    {
        if ( isset( $arr1[$i] ) )
            $final[] = $arr1[$i];
        if ( isset( $arr2[$i] ) )
            $final[] = $arr2[$i];
    }
    

    If you have named keys you can use the array_keys function for each array and loop over the array of keys instead.

    If you want more than two arrays (or variable number of arrays) then you might be able to use a nested loop (though I think you'd need to have $arr[0] and $arr[1] as the individual arrays).

    0 讨论(0)
  • 2020-11-27 22:13

    I would just use array_merge(), but that obviously depends on what exactly you do.

    This would append those arrays to each other, while elements would only be replaced when they have the same non-numerical key. And that might not be a problem for you, or it might be possible to be solved because of attribute order, since the contents of the first arrays' elements will be overwritten by the later ones.

    0 讨论(0)
  • 2020-11-27 22:19

    for example,

    function array_zip_merge() {
      $output = array();
      // The loop incrementer takes each array out of the loop as it gets emptied by array_shift().
      for ($args = func_get_args(); count($args); $args = array_filter($args)) {
        // &$arg allows array_shift() to change the original.
        foreach ($args as &$arg) {
          $output[] = array_shift($arg);
        }
      }
      return $output;
    }
    
    // test
    
    $a = range(1, 10);
    $b = range('a', 'f');
    $c = range('A', 'B');
    echo implode('', array_zip_merge($a, $b, $c)); // prints 1aA2bB3c4d5e6f78910
    
    0 讨论(0)
  • 2020-11-27 22:37

    If you have n arrays, you could use a SortedList, and use arrayIndex * n + arrayNumber as a sort index.

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