Is there better way to transpose a PHP 2D array?

后端 未结 3 1691
[愿得一人]
[愿得一人] 2020-12-11 02:22

According to the PHP Manual, calling array_map with a NULL callback causes it to perform a \"zip\" function, creating an array of arrays of paralle

相关标签:
3条回答
  • 2020-12-11 02:48

    Nope. That's the most elegant.

    0 讨论(0)
  • 2020-12-11 02:55

    Update for PHP 5.6:

    We can take advantage of PHP 5.6's "splat" operator to make this operation much, much cleaner with argument unpacking:

    array_map(null, ...$array_of_arrays);
    

    For example:

    [1] boris> $arr2d = [ [1,2,3], ['a','b','c'] ];
    // array(
    //   0 => array(
    //     0 => 1,
    //     1 => 2,
    //     2 => 3
    //   ),
    //   1 => array(
    //     0 => 'a',
    //     1 => 'b',
    //     2 => 'c'
    //   )
    // )
    [2] boris> array_map(null, ...$arr2d);
    // array(
    //   0 => array(
    //     0 => 1,
    //     1 => 'a'
    //   ),
    //   1 => array(
    //     0 => 2,
    //     1 => 'b'
    //   ),
    //   2 => array(
    //     0 => 3,
    //     1 => 'c'
    //   )
    // )
    
    0 讨论(0)
  • 2020-12-11 02:55

    If you really want to avoid the array_merge, use array_unshift to prepend the NULL to the $array_of_arrays instead:

    array_unshift($array_of_arrays, NULL);
    call_user_func_array('array_map', $array_of_arrays);
    

    Of course it is not a one-liner anymore :P

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