Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor (transpose) array to unique keys [duplicate]

I'm transposing some db results for statistic generation.

Original array:

Array
(
    [0] => Array
        (
            [a] => apple
            [b] => beer
            [c] => chocolate
        )
    [1] => Array
        (
            [a] => aardvark
            [b] => bear
            [c] => chupacabra
        )
)

Desired result:

Array
(
    [a] => Array
        (
            [0] => apple
            [1] => aardvark
        )
    [b] => Array
        (
            [0] => beer
            [1] => bear
        )

    [c] => Array
        (
            [0] => chocolate
            [1] => chupacabra
        )
)

Sample code:

$stats[] = array(
    'a' => 'apple',
    'b' => 'beer',
    'c' => 'chocolate'
);

$stats[] = array(
    'a' => 'aardvark',
    'b' => 'bear',
    'c' => 'chupacabra'
);

foreach (array_keys($stats[0]) as $key){
    $data[$key] = array_column($stats, $key);
}

The above code is working fine using array_keys and array_column (php 5.5).

  • Is there a more elegant way or php function to achieve the same result?

  • What is the common name for this kind of re-factoring?

EDIT:

As per comments below the correct term for this is "transposing"

like image 420
Makita Avatar asked Aug 05 '26 10:08

Makita


1 Answers

I had thought there was an array_* function for that sort of thing, but I couldn't remember so I went to the PHP documentation Turns out that array_merge_recursive does just what you want.

array_merge_recursive($array1, $array2)

You have your arrays to combine in a single array, so you'll have to populate the function's arguments with the contents of the array.

call_user_func_array("array_merge_recursive", $stats)

That one line should do what you are looking for.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!