3

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"

Makita
  • 1,812
  • 12
  • 15

1 Answers1

3

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.