PHP: array_merge() in alternate order (zip order)?

2020-02-16 02:06发布

问题:

Is there a native PHP function to zip merge two arrays?

Look at the following example:

$a = array("a","b","c");
$b = array("d","e","f");
$c = array("g","h","i");

var_dump(array_merge($a,$b,$c));

This produces:

array(9) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
  [6]=>
  string(1) "g"
  [7]=>
  string(1) "h"
  [8]=>
  string(1) "i"
}

However I want:

array(9) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "d"
  [2]=>
  string(1) "g"
  [3]=>
  string(1) "b"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "h"
  [6]=>
  string(1) "c"
  [7]=>
  string(1) "f"
  [8]=>
  string(1) "i"
}

Therfore I wrote my own - tested an working - function:

function array_zip(...$arrays) {
    $res = array();

    while(true) {
        $check_finish = true;
        foreach($arrays as $array) {
            if(!empty($array)) {
                $check_finish = false;
            }
        }

        if($check_finish) {
            break;
        } else {

            foreach($arrays as $key => $array) {
                if(!empty($array)) {
                    array_push($res,array_shift($array)); 
                    $arrays[$key] = $array;
                }
            }
        }
    }

    return $res;
}

However is there a native PHP function to merge arrays like this (maybe more performant)? And is there a native PHP function for this purpose which preserves keys but keeps the order? Did not find sth :-/

回答1:

There is no PHP native function for this purpose. However according to the comment of @Mark Baker there is a short possibility to implement this:

$a = array("a","b","c");
$b = array("d","e","f");
$c = array("g","h","i");

function array_zip(...$arrays) {
    return array_merge(...array_map(null, ...$arrays));
}

var_dump(array_zip($a,$b,$c));