PHP merge multiple arrays in order of their value

2019-08-09 18:59发布

问题:

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