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"