使用 array_diff 后以对象形式获取答案

我正在比较 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”]}


噜噜哒
浏览 91回答 1
1回答

慕田峪7331174

array_diff保留原始数组的键。您需要重新初始化数组,以使 json 中没有数组键。您可以使用array_values来获取重新初始化的数组键<?php&nbsp; &nbsp; &nbsp; &nbsp;$schedule =&nbsp; ['Monday'=>['12:00','01:20'],'Tuesday'=>['04:00','12:00','20:00']];&nbsp; &nbsp; &nbsp; &nbsp;$booked_slots =&nbsp; ['Monday'=>['12:00'],'Tuesday'=>['20:00']];&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;$diff = [];&nbsp; &nbsp; &nbsp; &nbsp;foreach ($schedule as $day =>&nbsp; $times) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$day_wise_slots = isset($booked_slots[$day]) ? $booked_slots[$day] : [];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$diff[$day] = array_values(array_diff($times, $day_wise_slots));&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;echo json_encode($diff);?>
打开App,查看更多内容
随时随地看视频慕课网APP