Refactoring (transposing) to unique keys

I am transferring some db results to generate statistics.

The 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
        )
)

Code example:

$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 works 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:

According to the comments below, the correct term for this is “transpose”

+4
source share
1 answer

, array_*, , PHP. , array_merge_recursive , .

array_merge_recursive($array1, $array2)

, .

call_user_func_array("array_merge_recursive", $stats)

, .

+3

All Articles