简体   繁体   English

PHP按其值索引的顺序合并多个数组

[英]PHP merge multiple arrays in order of their value index

I've found a lot of information on joining arrays together using array_merge , but I'm wondering how easy it is to merge multiple arrays in order of their value index, rather than simply joining them together. 我发现了很多关于使用array_merge连接数组的信息,但是我想知道按照它们的值索引合并多个数组是多么容易,而不是简单地将它们连接在一起。

For example, if we had the following three arrays: 例如,如果我们有以下三个数组:

$a = array('One','Two','Three','Four');
$b = array(1,2,3,4);
$c = array('i','ii','iii','iv');

Could we merge them into?: 我们可以合并它们吗?:

One,1,i,Two,2,ii,Three,3,iii,Four,4,iv

Instead of: 代替:

One, Two, Three, Four, 1, 2, 3, 4, i, ii, iii, iv

you can write your custom function like this. 你可以像这样编写自定义函数。

$a = array('One','Two','Three','Four');
$b = array(1,2,3,4);
$c = array('i','ii','iii','iv');

$count = max(count($a), count($b), count($c));
$newarray = array();

for($i=0; $i < $count; $i++) {
   if (isset($a[$i])) $newarray[] = $a[$i];
   if (isset($b[$i])) $newarray[] = $b[$i];
   if (isset($c[$i])) $newarray[] = $c[$i];
}

var_dump($newarray);

I wouldn't actually use this code due to readability, but it's cool that it works. 由于可读性,我实际上不会使用此代码,但它的工作原理很酷。

Make an array of arrays first 首先创建一个数组数组

$a = array('One','Two','Three','Four');
$b = array(1,2,3,4);
$c = array('i','ii','iii','iv');
$arrays = [$a, $b, $c];

then 然后

array_unshift($arrays, null);
$n = call_user_func_array('array_merge', call_user_func_array('array_map', $arrays));
print_r($n);

yields 产量

Array
(
    [0] => One
    [1] => 1
    [2] => i
    [3] => Two
    [4] => 2
    [5] => ii
    [6] => Three
    [7] => 3
    [8] => iii
    [9] => Four
    [10] => 4
    [11] => iv
)

demo http://codepad.org/FdZKffPQ 演示http://codepad.org/FdZKffPQ

it makes use of this matrix transpose method https://stackoverflow.com/a/3423692 它利用了这种矩阵转置方法https://stackoverflow.com/a/3423692

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM