Search code examples
phparraysmultidimensional-arraytransposeflatten

Merge columns from multiple multidimensional arrays to generate a flat array


Here is my arrays after array chunk by 2

$a = [["testA1", "testA2"], ["testA3", "testA4"]];
$b = [["testB1", "testB2"], ["testB3", "testB4"]];
$c = [["testC1", "testC2"], ["testC3", "testC4"]];

I want to merge these arrays in below format.

$result = array(
    "testA1",
    "testA2",
    "testB1",
    "testB2",
    "testC1",
    "testC2",
    "testA3",
    "testA4",
    "testB3",
    "testB4",
    "testC3",
    "testC4"
);

Is there any in-built function available or how to solve this?.


Solution

  • Use array_merge twice with ... syntax:

    print_r(array_merge(...array_merge($a, $b, $c)));
    
    // 2nd version
    $parts = [];
    foreach($a as $k => $v) {
        $parts[$k] = array_merge($a[$k], $b[$k], $c[$k]);
    }
    print_r(array_merge(...$parts));
    
    // hard to understand version:
    $parts = array_map(null, $a, $b, $c);
    print_r(array_merge(...array_merge(...$parts)));