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
2
  • 1
    I don't think there's a built-in function for this, just write a for loop. Commented Jun 30, 2013 at 2:43
  • what is the purpose? You are going to have to make your own custom merge function Commented Jun 30, 2013 at 2:44

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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
Thanks, this does the trick quite nicely. The arrays will always be identical in length in my application :)
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.