慕尼黑的夜晚无繁华
这是一个不错的小技巧,假设数组/对象的结构包含“项目”。工作示例:https : //3v4l.org/Wat8i 适用于 PHP 5.4+。<?php$datetimes = [ "items" => [ [ "id" => 1, "start_date" => "2019-09-26", "start_time" => "07:00:00", "end_date" => "2019-09-26", "end_time" => "09:00:00" ], [ "id" => 4, "start_date" => "2019-09-26", "start_time" => "12:00:00", "end_date" => "2019-09-26", "end_time" => "14:00:00" ], [ "id" => 9, "start_date" => "2019-09-26", "start_time" => "16:00:00", "end_date" => "2019-09-26", "end_time" => "17:00:00" ], [ "id" => 13, "start_date" => "2019-09-26", "start_time" => "19:00:00", "end_date" => "2019-09-26", "end_time" => "20:00:00" ], [ "id" => 2, "start_date" => "2019-09-27", "start_time" => "07:00:00", "end_date" => "2019-09-27", "end_time" => "08:00:00" ], [ "id" => 5, "start_date" => "2019-09-27", "start_time" => "12:00:00", "end_date" => "2019-09-27", "end_time" => "14:00:00" ], [ "id" => 10, "start_date" => "2019-09-27", "start_time" => "16:00:00", "end_date" => "2019-09-27", "end_time" => "18:00:00" ], [ "id" => 14, "start_date" => "2019-09-27", "start_time" => "19:00:00", "end_date" => "2019-09-27", "end_time" => "20:00:00" ], [ "id" => 3, "start_date" => "2019-09-28", "start_time" => "07:00:00", "end_date" => "2019-09-28", "end_time" => "10:00:00" ], [ "id" => 6, "start_date" => "2019-09-28", "start_time" => "12:00:00", "end_date" => "2019-09-28", "end_time" => "13:00:00" ], [ "id" => 11, "start_date" => "2019-09-28", "start_time" => "16:00:00", "end_date" => "2019-09-28", "end_time" => "17:00:00" ], [ "id" => 15, "start_date" => "2019-09-28", "start_time" => "19:00:00", "end_date" => "2019-09-28", "end_time" => "20:00:00" ] ]];$openinghours = [];function openinghours($times) { global $openinghours; $openinghours[$times["start_date"]][] = [ "start" => $times["start_time"], "end" => $times["end_time"] ];}array_map("openinghours", $datetimes["items"]);var_dump($openinghours);它基本上是在不修改旧数组的情况下创建一个新数组,也不需要 if 语句。[编辑1]foreach()以及快速显示日期和时间的附加功能: https ://3v4l.org/uhUeSforeach($openinghours as $date => $times) { echo "{$date} : {$times[0]["start"]} - " . end($times)["end"] . "\n";}[编辑2]如果您希望人们或您自己更改营业时间以便id 1不得不这样07:00:00做20:00:00,我建议您将输出结构更改为忽略start,end然后只选择日期的第一个和最后一个:https ://3v4l.org/jMvCPfunction openinghours($times) { global $openinghours; $openinghours[$times["start_date"]][] = $times["start_time"]; $openinghours[$times["start_date"]][] = $times["end_time"]; sort($openinghours[$times["start_date"]]);}array_map("openinghours", $datetimes["items"]);var_dump($openinghours);foreach($openinghours as $date => $times) { echo "{$date} : {$times[0]} - " . end($times) . "\n";}