PHP merge multiple arrays in order of their value index

て烟熏妆下的殇ゞ 提交于 2019-12-24 14:43:02

问题


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.

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

回答1:


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



回答2:


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

it makes use of this matrix transpose method https://stackoverflow.com/a/3423692



来源:https://stackoverflow.com/questions/17386630/php-merge-multiple-arrays-in-order-of-their-value-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!