Search code examples
phparraystransposeflattenarray-merge

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.

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

Solution

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