1 回答
TA贡献1839条经验 获得超15个赞
是的你可以。由于您id
似乎是唯一的,因此迭代它并使用您的id
索引作为主索引创建新数组,您可以使用array_key_exists()来执行此操作。毕竟它应该看起来像这样:
array(2){
[6]=>array() {
['id']=> "6"
['name']=>"peter"
["dates" => [2020-09-25, 2020-09-26, 2020-09-27]]
["sleeps" => [20, 80, 40]]
["pains" => [30, 90, 60]]
[10]=>array() {
['id']=> "10"
['name']=>"john"
["dates" => [2022-09-25, 2022-09-25]]
["sleeps" => [25, 55]]
["pains" => [15, 65]]
}
这是 5 分钟的工艺,我很确定你会自己做。
<?php
$data = [
[
'id' => '6',
'name' => 'peter',
'date' => '2020-09-25',
'sleep' => '20',
'pain' => '30'
],
[
'id' => '6',
'name' => 'peter',
'date' => '2020-09-26',
'sleep' => '80',
'pain' => '90',
],
[
'id' => '10',
'name' => 'john',
'date' => '2022-09-25',
'sleep' => '25',
'pain' => '15',
],
[
'id' => '10',
'name' => 'john',
'date' => '2022-09-25',
'sleep' => '55',
'pain' => '65',
],
[
'id' => '6',
'name' => 'peter',
'date' => '2020-09-27',
'sleep' => '40',
'pain' => '60'
]
];
$newArr = [];
foreach ($data as $oldItem) {
$id = $oldItem['id'];
if (!array_key_exists($id, $newArr)) {
$newArr[$id] = [
'id' => $id,
'name' => $oldItem['name'],
'dates' => [$oldItem['date']],
'sleeps' => [$oldItem['sleep']],
'pains' => [$oldItem['pain']],
];
} else {
$newArr[$id]['dates'][] = $oldItem['date'];
$newArr[$id]['sleeps'][] = $oldItem['sleep'];
$newArr[$id]['pains'][] = $oldItem['pain'];
};
}
echo "<pre>JSON:\n";
echo json_encode($newArr, JSON_PRETTY_PRINT);
echo "\n\nprint_r():\n";
print_r($newArr);
- 1 回答
- 0 关注
- 117 浏览
添加回答
举报