Laravel中合并API获取的同日期同服务日程数据并统计
解决方案
1. 后端分组处理(控制器中)
先对API返回的数据做分组统计,确保同一日期、同一服务的记录被合并:
// 假设$response是Laravel Http Client返回的响应实例 $schedules = collect($response->json()); // 按「日期+服务ID」分组,避免服务代码相同但实际为不同服务的错误合并 $groupedSchedules = $schedules->groupBy(function ($schedule) { return $schedule['date'] . '|' . $schedule['serviceTimeRange']['service']['id']; })->map(function ($group) { // 提取每组公共信息,同时统计该组的时间段数量 return [ 'date' => $group[0]['date'], 'serviceCode' => $group[0]['serviceTimeRange']['service']['serviceCode'], 'timeSlotCount' => $group->count() ]; }); // 将分组后的数据传递给视图 return view('your-view-name', compact('groupedSchedules'));
2. 前端Blade模板渲染
在视图中循环处理后的数据,输出目标格式:
@foreach($groupedSchedules as $item) {{ date('d-M-Y', strtotime($item['date'])) }} {{ $item['serviceCode'] }} {{ $item['timeSlotCount'] }} // 对应服务的时间段数量 <br><br> @endforeach
如果需要表格形式输出,可调整为:
<table> <thead> <tr> <th>日期</th> <th>服务代码</th> <th>时间段数量</th> </tr> </thead> <tbody> @foreach($groupedSchedules as $item) <tr> <td>{{ date('d-M-Y', strtotime($item['date'])) }}</td> <td>{{ $item['serviceCode'] }}</td> <td>{{ $item['timeSlotCount'] }}</td> </tr> @endforeach </tbody> </table>
补充说明
- 用「日期+服务ID」作为分组键,是为了规避服务代码重复但实际为不同服务的场景;若确认服务代码全局唯一,也可直接用「日期+服务代码」分组。
map方法负责提取每组的公共数据,并通过count()统计该组的时间段数量。
内容的提问来源于stack exchange,提问作者user2519032
相关产品推荐
相关产品推荐

