Search code examples
phparraystransposeflattenarray-merge

How can I merge multiple flat arrays of unknown length, transpose them, then form a 1-dimensional array?


I have 3 arrays like this:

$a = array(
 0 => 'a1',
 1 => 'a2',
 2 => 'a3'
);

$b = array(
 0 => 'b1',
 1 => 'b2',
 2 => 'b3'
);

$c = array(
 0 => 'c1',
 1 => 'c2',
 2 => 'c3'
);

and I like to have something like this:

$r = array(
 0 => 'a1',
 1 => 'b1',
 2 => 'c1',
 3 => 'a2',
 4 => 'b2',
 5 => 'c2',
 6 => 'a3',
 ....
 ...
);

How can I do this AND enjoy the ability to use more then 3 input arrays?

EDIT:

I have tried this:

$a = array(
        0 => 'a1',
        1 => 'a2',
        2 => 'a3',
        3 => 'a4'
    );
    $b = array(
        0 => 'b1',
        1 => 'b2',
        2 => 'b3'
    );
    $c = array(
        0 => 'c1',
        1 => 'c2',
        2 => 'c3',
        3 => 'c4',
        4 => 'c5',
        5 => 'c6'

    );

    $l['a'] = count($a);
    $l['b'] = count($b);
    $l['c'] = count($c);

    arsort($l);
    $largest = key($l);
    $result = array();
    foreach ($$largest as $key => $value) {
        $result[] = $a[$key];
        if(array_key_exists($key, $b)) $result[] = $b[$key];
        if(array_key_exists($key, $c)) $result[] = $c[$key];

    }
    print_r($result);

Output: Array ( [0] => a1 [1] => b1 [2] => c1 [3] => a2 [4] => b2 [5] => c2 [6] => a3 [7] => b3 [8] => c3 [9] => a4 [10] => c4 [11] => [12] => c5 [13] => [14] => c6 )

This works but the code isn't nice. Does anyone have a better solution?

Solution: I updated the post from @salathe with some dynamic feature

function comb(){
    $arrays = func_get_args();
    $result = array();
    foreach (call_user_func_array(array_map, $arrays) as $column) {
        $values = array_filter($column, function ($a) { return $a !== null; });
        $result = array_merge($result, $values);
    }
    return $result;
}
print_r(comb(null,$a,$b,$c,$d,....));

Solution

  • You could make use the array_map() function to do most of the hard work.

    In the example, the code inside the loop just takes the value from each array (null if there is not a corresponding value) and if there is a value, appends them to the $results array.

    Example

    $result = array();
    foreach (array_map(null, $a, $b, $c) as $column) {                                          
        $values = array_filter($column, function ($a) { return $a !== null; });
        $result = array_merge($result, $values);
    }
    var_export($result);
    

    Output

    array (
      0 => 'a1',
      1 => 'b1',
      2 => 'c1',
      3 => 'a2',
      4 => 'b2',
      5 => 'c2',
      6 => 'a3',
      7 => 'b3',
      8 => 'c3',
      9 => 'a4',
      10 => 'c3',
      11 => 'c3',
      12 => 'c3',
    )