PHP嵌套数组处理以创建日期键和值

问题描述 投票:0回答:1

我有一个PHP项目,其中管理这样定义的数据结构(在$data变量中:

array:35 [▼
  "2020-03-16" => array:12 [▼
    "00:00:00" => 17.185
    "02:00:00" => 17.235
    "04:00:00" => 17.25
    "06:00:00" => 16.905
    "08:00:00" => 21.205
    "10:00:00" => 23.47
    "12:00:00" => 24.42
    "14:00:00" => 27.245
    "16:00:00" => 30.94
    "18:00:00" => 30.78
    "20:00:00" => 29.735
    "22:00:00" => 28.64
  ]
  "2020-03-17" => array:12 [▼
    "00:00:00" => 29.985
    "02:00:00" => 32.455
    "04:00:00" => 31.28
    "06:00:00" => 34.33
    "08:00:00" => 29.755
    "10:00:00" => 26.92
    "12:00:00" => 29.72
    "14:00:00" => 28.36
    "16:00:00" => 30.815
    "18:00:00" => 34.605
    "20:00:00" => 34.315
    "22:00:00" => 33.125
  ]
  "2020-03-18" => array:12 [▶]
...
]

它们来自外部服务,因此我无法在原始位置进行修改。我需要“重写” $data,以便最终得到类似以下内容的东西:

array:420 [▼
"2020-03-16 00:00:00" => 17.185
"2020-03-16 02:00:00" => 17.235
"2020-03-16 04:00:00" => 17.25
...
"2020-03-20 00:00:00" => 22.675
"2020-03-20 02:00:00" => 24.67
...
]

您能告诉我一个聪明的方法吗?提前非常感谢。

php arrays multidimensional-array nested
1个回答
0
投票

仅使用数据结构,我找到了解决方案:

$cleanData = [];
foreach ($data as $day => $arr) {
    foreach ($arr as $hour => $value)
        $cleanData[$day.' '.$hour] = $value;
}

是一些增强功能还是更智能的方法?您如何看待解决方案?再次感谢。

© www.soinside.com 2019 - 2024. All rights reserved.