Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the PHP array_walk function to rearrange keys in a multidimensional array?

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?

like image 431
user12148446 Avatar asked Jan 25 '23 18:01

user12148446


2 Answers

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

like image 171
Anant Kumar Singh Avatar answered Jan 28 '23 09:01

Anant Kumar Singh


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);
like image 34
u_mulder Avatar answered Jan 28 '23 09:01

u_mulder