4

我有一个以下格式的 PHP 数组:

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

我正在尝试使用 PHP 中的 array_walk() 函数来重新排列数组键,如下所示:

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

我正在使用以下代码来执行此操作:

$result_arr = [];   
array_walk($myArray,function($v,$k) use (&$result_arr){
  $result_arr[key($v)][$k] = $v[key($v)];
});

但是我目前使用的这段代码只产生第一个项目 A,并且不产生以下项目 B 和 CIe 我希望得到完整的输出,但只收到第一个项目,如下所示:

array (size=1)
 'A' => 
   array (size=2)
    '2019-09-28' => float 4
    '2019-09-29' => float 5

请帮忙。我错过了什么?

4

4 回答 4

3

你也需要在forach()那里申请:

$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);

输出:https ://3v4l.org/fJJhm

于 2019-10-01T13:27:00.980 回答
3

foreach解决方案,在这里摆弄:

$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);
于 2019-10-01T13:27:30.603 回答
1

I think array_walk would be best used for modifying values in an array instead of messing with the array's structure. I'd personally use array_reduce to aggregate information of a given array to form another one with a completely different structure (i.e. your use case)

<?php

$array = [
        '2019-09-28' => [
                'A' => (float) 4,
                'B' => (float) 85,
                'C' => (float) 200,
        ],
        '2019-09-29' => [
                'A' => (float) 5,
                'B' => (float) 83,
                'C' => (float) 202,
        ],
];

$result = array_reduce(array_keys($array), function ($result, $date) use ($array) {
        return array_reduce(array_keys($array[$date]), function ($result, $key) use ($array, $date) {
                $result[$key][$date] = $array[$date][$key];
                return $result;
        }, $result);
}, []);

var_dump($result);

Demonstrated in PHP Sandbox.

于 2019-10-01T13:39:42.480 回答
1

你可以接近这是

 array_walk($a, function($v,$k) use (&$r){
    array_walk($v,function($v1,$k1) use (&$r,$k){
    $r[$k1][$k] = $v1;
  });
});
print_r($r);

工作示例:https ://3v4l.org/An23C

于 2019-10-01T13:27:42.320 回答