1

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
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
James Mathieson
  • 419
  • 2
  • 5
  • 22

2 Answers2

2

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);
DevZer0
  • 13,433
  • 7
  • 27
  • 51
  • 1
    This assumes all the arrays are the same length. Better to do `$count = max(count($a), count($b), count($c));` and then do an `isset()` on each array before attempting to add an index to `$newarray` – Steven Moseley Jun 30 '13 at 02:59
  • Thanks, this does the trick quite nicely. The arrays will always be identical in length in my application :) – James Mathieson Jun 30 '13 at 03:18
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

Community
  • 1
  • 1
goat
  • 31,486
  • 7
  • 73
  • 96