dousuohe5882 2016-11-08 12:51
浏览 49
已采纳

如何在PHP中合并多个数组但将值混合在一起 - 保留它们的顺序

Is there a straightforward way in PHP to combine multiple arrays together but respect the relative order of the elements?

So for example if I had two arrays

$x = ('1','2','3','4');

and

$y = array('a','b','c','d','e');

and I wanted combine them into a single array

$z = ('1','a','2','b','3','c','4','d','e');

Is there a straightforward way of doing this? The ideal solution would also account for different lengths of arrays, behaving as my example does.

array_merge doesn't seem to achieve what I want as it just appends one array to the other.

My current solution loops through each array in order and pushes values to my $z array. This is not only inelegant, it also requires the input arrays to have the same number of values, which isn't ideal for my application.

Any insight would be appreciated

  • 写回答

4条回答 默认 最新

  • dongmi4720 2016-11-08 13:53
    关注

    You could use this generic function, which can accept any number of arrays, and will output an array with the elements taken from the first "column" first, then from the second, etc:

    function mix_merge(...$args) {
        return call_user_func_array('array_merge', 
            array_map(function($i) use ($args) { return array_column($args, $i); },
                      range(0, max(array_map('count', $args))-1)));
    }
    
    
    // Sample data:
    $x = array('1','2','3','4');
    $y = array('a','b','c','d','e');    
    $z = array('A','B','C');    
    
    $res = mix_merge($x, $y, $z);
    

    Result array will be:

    ['1', 'a', 'A', '2', 'b', 'B', '3', 'c', 'C', '4', 'd', 'e']
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 51寻迹小车定点寻迹
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错