交错多个阵列成一个阵列 [英] Interleaving multiple arrays into a single array

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

问题描述

我需要几个阵列合并成一个单一的阵列。最好的办法来形容我正在寻找的是交错的数组到一个单一的阵列。

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天全站免登陆