将多个数组交织成一个数组 [英] Interleaving multiple arrays into a single array

查看:28
本文介绍了将多个数组交织成一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将多个数组合并为一个数组.描述我正在寻找的最好方法是将数组交错"成一个数组.

I need to merge several arrays into a single array. The best way to describe what I'm looking for is "interleaving" the arrays into a single array.

例如,从数组 #1 中取出第一个项并附加到最​​终数组.从数组 #2 中获取第一项并附加到最​​终数组.从数组#1 中获取第二项并追加...等

For example take item one from array #1 and append to the final array. Get item one from array #2 and append to the final array. Get item two from array #1 and append...etc.

最终的数组看起来像这样:

The final array would look something like this:

数组#1.element#1数组#2.element#1...

array#1.element#1 array#2.element#1 . . .

踢球者"是单个数组可以有不同的长度.

The "kicker" is that the individual arrays can be of various lengths.

有没有更好的数据结构可以使用?

Is there a better data structure to use?

推荐答案

例如,

function array_zip_merge() {
  $output = array();
  // The loop incrementer takes each array out of the loop as it gets emptied by array_shift().
  for ($args = func_get_args(); count($args); $args = array_filter($args)) {
    // &$arg allows array_shift() to change the original.
    foreach ($args as &$arg) {
      $output[] = array_shift($arg);
    }
  }
  return $output;
}

// test

$a = range(1, 10);
$b = range('a', 'f');
$c = range('A', 'B');
echo implode('', array_zip_merge($a, $b, $c)); // prints 1aA2bB3c4d5e6f78910

这篇关于将多个数组交织成一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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