转置和展平多行数组数据 [英] Transpose and flatten multiple rows of array data

查看:40
本文介绍了转置和展平多行数组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有原生 PHP 函数来压缩合并两个数组?

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

看下面的例子:

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

因此我编写了自己的 - 测试了一个工作 - 功能:

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

但是,是否有本机 PHP 函数来合并这样的数组(可能性能更高)?是否有用于此目的的本机 PHP 函数可以保留键但保留顺序?没有找到…… :-/

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 :-/

推荐答案

没有为此目的的 PHP 原生函数.然而,根据@Mark Ba​​ker 的评论,实现这一点的可能性很小:

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

这篇关于转置和展平多行数组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆