I have a PHP array in the following format:
array (size=2)
'2019-09-28' =>
array (size=2)
'A' => float 4
'B' => float 85
'C' => float 200
'2019-09-29' =>
array (size=2)
'A' => float 5
'B' => float 83
'C' => float 202
I'm trying to use the array_walk() function in PHP to rearrange the array keys as follows:
array (size=3)
'A' =>
array (size=2)
'2019-09-28' => float 4
'2019-09-29' => float 5
'B' =>
array (size=2)
'2019-09-28' => float 85
'2019-09-29' => float 83
'C' =>
array (size=2)
'2019-09-28' => float 200
'2019-09-29' => float 202
I'm using the following code to do so:
$result_arr = [];
array_walk($myArray,function($v,$k) use (&$result_arr){
$result_arr[key($v)][$k] = $v[key($v)];
});
But this code that I'm currently using produces ONLY the first item A, and doesn't produce the following items B and C. I.e. I expect the full output but only receive the first item as follows:
array (size=1)
'A' =>
array (size=2)
'2019-09-28' => float 4
'2019-09-29' => float 5
Please help. What am I missing?
You need to apply forach()
there too:
$result_arr = [];
array_walk($myArray,function($value,$key) use (&$result_arr){
foreach($value as $k=> $val){ //$value is an array, so iterate over it
$result_arr[$k][$key] = $val;
}
});
print_r($result_arr);
Output: https://3v4l.org/fJJhm
foreach
solution, fiddle here:
$array = [
'2019-09-28' => [
'A' => 4,
'B' => 85,
'C' => 200,
],
'2019-09-29' => [
'A' => 5,
'B' => 83,
'C' => 202,
]
];
$res = [];
foreach ($array as $key => $item) {
foreach ($item as $itemKey => $itemValue) {
$res[$itemKey][$key] = $itemValue;
}
}
print_r($res);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With