Search code examples
phparraysmultidimensional-arraytransposeimplode

How to transpose and implode subarray data within a multidimensional array to create a flat output array?


I don't have a specified number of subarrays, but my data structure can look like this:

array(("john","alex","tyler"),("1","2","3"),("brown","yellow","green"));

The above example has 3 subarrays, but the problem is this number can change.

As a final output I need, in this example, an array with 3 strings.

array("john,1,brown","alex,2,yellow","tyler,3,green");

I've tried to write this with functions, but couldn't find a solution.


Solution

  • The solution using call_user_func_array, array_map and array_merge functions:

    $arr = [["john","alex","tyler"],["1","2","3"],["brown","yellow","green"]];
    
    $groups = call_user_func_array("array_map", array_merge([null], $arr));
    $result = array_map(function ($v) {
        return implode(",", $v);
    }, $groups);
    
    print_r($result);
    

    The output:

    Array
    (
        [0] => john,1,brown
        [1] => alex,2,yellow
        [2] => tyler,3,green
    )
    

    http://php.net/manual/en/function.call-user-func-array.php