我正在比较 2 个数组,但在应用 array_diff 后,它以对象形式返回结果。看看下面的代码和结果<?php $schedule = ['Monday'=>['12:00','01:20'],'Tuesday'=>['04:00','12:00','20:00']]; $booked_slots = ['Monday'=>['12:00'],'Tuesday'=>['20:00']]; $diff = []; foreach ($schedule as $day => $times) { $day_wise_slots = isset($booked_slots[$day]) ? $booked_slots[$day] : []; $diff[$day] = array_diff($times, $day_wise_slots); } echo json_encode($diff);?>结果:{"星期一":{"1":"01:20"},"星期二":["04:00","12:00"]}所需输出:{“星期一”:[“01:20”],“星期二”:[“04:00”,“12:00”]}
1 回答
慕田峪7331174
TA贡献1828条经验 获得超13个赞
array_diff保留原始数组的键。您需要重新初始化数组,以使 json 中没有数组键。您可以使用array_values来获取重新初始化的数组键
<?php
$schedule = ['Monday'=>['12:00','01:20'],'Tuesday'=>['04:00','12:00','20:00']];
$booked_slots = ['Monday'=>['12:00'],'Tuesday'=>['20:00']];
$diff = [];
foreach ($schedule as $day => $times) {
$day_wise_slots = isset($booked_slots[$day]) ? $booked_slots[$day] : [];
$diff[$day] = array_values(array_diff($times, $day_wise_slots));
}
echo json_encode($diff);
?>
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报
0/150
提交
取消