Reputation: 1533
I have a multi dimensional array that I want to invert / reverse. My array contains in the first index 7 days of the week as dates. and each of these days has 16 different records within. I want to convert this into a result of 16 primary results, within these would lie the 7 days of results after. So from
'2015-04-28' => array(
(int) 1 => (float) 1,
(int) 2 => (float) 0.5,
(int) 3 => (float) 0,
(int) 4 => (float) 0,
(int) 5 => (float) 1,
(int) 6 => (float) 1,
(int) 7 => (float) 0.66666666666667,
(int) 8 => (float) 1,
(int) 9 => (float) 0.66666666666667,
(int) 10 => (float) 0.5,
(int) 11 => (float) 1,
(int) 12 => (float) 0.5,
(int) 13 => (float) 1,
(int) 14 => (float) 0,
(int) 15 => (float) 0.5,
(int) 16 => (float) 1
),
to
array(
(int) 1 => array(
'2015-04-27' => (float) 1,
'2015-04-28' => (float) .67,
'2015-04-29' => (float) .5
),
(int) 2 => array(
'2015-04-27' => (float) 1,
'2015-04-28' => (float) .67,
'2015-04-29' => (float) .5
),
(int) 3 => array(
'2015-04-27' => (float) 1,
'2015-04-28' => (float) .67,
'2015-04-29' => (float) .5
),
(int) 4 => array(
'2015-04-27' => (float) 1,
'2015-04-28' => (float) .67,
'2015-04-29' => (float) .5
),
);
and so on. Is there a php function available to do this, or would I need to convert this manually?
Upvotes: 0
Views: 536
Reputation: 2706
It is not very hard once you get the hang of associative array. You can create a new array, and fill the values in a loop like so:
function transposeArray($arr) {
$result = array();
foreach ($arr as $mKey => $subArr) {
foreach ($subArr as $sKey => $sVal) {
$result[$sKey][$mKey] = $sVal;
}
}
return $result;
}
Upvotes: 1