PHP:array_merge()以交替顺序(zip顺序)?

时间:2017-04-25 18:43:05

标签: php arrays array-merge

是否有本地PHP函数来压缩合并两个数组?

请看以下示例:

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

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

这会产生:

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"
}

但是我想:

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"
}

因此我写了自己的 - 测试了一个工作函数:

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;
}

然而,有一个本机PHP函数来合并这样的数组(可能更高性能)?是否有用于此目的的本机PHP功能,它保留了密钥但保留了订单?没找到......:/ /

1 个答案:

答案 0 :(得分:0)

没有用于此目的的PHP本机功能。但是根据@Mark Ba​​ker的评论,实现这一点的可能性很小:

$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));