Search code examples
phparraysmultidimensional-arraytranspose

Convert columns of a 2d array into rows of a 2d array


I have a array with x array in it with always same keys in these arrays .

Array
(
    [foo] => Array
        (
            [q] => "12r3"
            [w] => "3r45"
            [e] => "67e8"
        )
    [foo1] => Array
        (
            [q] => "féEt"
            [w] => "Ptmf"
            [e] => "4323"
        )
    [foo2] => Array
        (
            [q] => "axa"
            [w] => "dfvd"
            [e] => "hjh"
        )
)

and I need to merge all these arrays in one like:

[foo] => Array
(
     [q] => Array
       (
          [0] => "12r3",
          [1] => "féEt",
          [2] => "axa",
       )
     [w] => Array
       (
          [0] => "3r45",
          [1] => "Ptmf",
          [2] => "dfvd",
       )
    ...

How can I do that?

Thanks.


Solution

  • This should work for you:

    (Here I just go through the first array and grab all columns with array_column() from the entire array with the keys from the first array.)

    <?php
    
        $arr = [
    
            "foo" => [
                "q" => "12r3",
                "w" => "3r45",
                "e" => "67e8"
            ],
            "foo1" => [
                "q" => "féEt",
                "w" => "Ptmf",
                "e" => "4323"
            ],
            "foo2" => [
                "q" => "axa",
                "w" => "dfvd",
                "e" => "hjh"
            ]
        ];
    
    
    foreach($arr["foo"] as $k => $v) {
        $results[$k] = array_column($arr, $k);
    }
    
    print_r($results);
    
    ?>
    

    Output:

    Array
    (
        [q] => Array
            (
                [0] => 12r3
                [1] => féEt
                [2] => axa
            )
    
        [w] => Array
            (
                [0] => 3r45
                [1] => Ptmf
                [2] => dfvd
            )
    
        [e] => Array
            (
                [0] => 67e8
                [1] => 4323
                [2] => hjh
            )
    
    )