如何将数组转换为json对象?

我正在尝试将值推送到数组中,结果就像


[{"Monday":"11:30"},{"Monday":"12:00"},{"Monday":"23:00"},{"Tuesday":"11:30"},{"Tuesday":"12:00"},{"Tuesday":"23:00"}]

但我希望它成为一个对象



{


"Monday" : [ "11:30", "12:00", "23:00"]


"Tuesday" : ["11:30","12:00","23:00"]


}

这是我的代码片段


$timings = DoctorTimings::where('doctor_id', '=', $input['doctor_id'])->get();

$doctor_timings = [];


foreach($timings as $timing) {

    $day_id = $timing->day_id;

    $time_slot_id = $timing->time_slot_id;

    $day_id =  Days::where('id', '=', $day_id)->first()->day;

    $time_id = DB::table('time_slot')->where('id', '=', $time_slot_id)->select('time')->first()->time;  

    array_push($doctor_timings, array($day_id => $time_id));

}


$doctorTimings = json_encode($doctor_timings);


echo $doctorTimings;


慕侠2389804
浏览 95回答 1
1回答

侃侃无极

您可以使用mapToGroups获取请求的格式。但是我不知道你的表结构所以我得到了这些;[{"Monday":"11:30"},{"Monday":"12:00"},{"Monday":"23:00"},{"Tuesday":"11:30"},{"Tuesday":"12:00"},{"Tuesday":"23:00"}]放入集合中(假设你雄辩的集合像那样返回)$timings = collect([&nbsp; &nbsp; &nbsp; &nbsp; ["Monday" => "11:30"],&nbsp; &nbsp; &nbsp; &nbsp; ["Monday" => "12:00"],&nbsp; &nbsp; &nbsp; &nbsp; ["Monday" => "23:00"],&nbsp; &nbsp; &nbsp; &nbsp; ["Tuesday" => "11:30"],&nbsp; &nbsp; &nbsp; &nbsp; ["Tuesday" => "12:00"],&nbsp; &nbsp; &nbsp; &nbsp; ["Tuesday" => "23:00"]&nbsp; &nbsp; ]);&nbsp; &nbsp; return $timings->mapToGroups(function ($item) {&nbsp; &nbsp; &nbsp; &nbsp; $day = array_key_first($item);&nbsp; &nbsp; &nbsp; &nbsp; return [$day => $item[$day]];&nbsp; &nbsp; });打印这些;{&nbsp; "Monday": [&nbsp; &nbsp; "11:30",&nbsp; &nbsp; "12:00",&nbsp; &nbsp; "23:00"&nbsp; ],&nbsp; "Tuesday": [&nbsp; &nbsp; "11:30",&nbsp; &nbsp; "12:00",&nbsp; &nbsp; "23:00"&nbsp; ]}编辑:(你在网上发布的相同数组在这里使用+我用于解决方案的相同功能)$days = ["Monday", "Monday"];$time = ["11:30", "12:30"];$doctor_timings = [];for ($i = 0; $i < sizeof($days); $i++) {&nbsp; &nbsp; $day_id = $days[$i];&nbsp; &nbsp; $time_id = $time[$i];&nbsp; &nbsp; array_push($doctor_timings, [$day_id => $time_id]);}return collect($doctor_timings)->mapToGroups(function ($item) {&nbsp; &nbsp; $day = array_key_first($item);&nbsp; &nbsp; return [$day => $item[$day]];});哪个打印{"Monday":["11:30","12:30"]}
打开App,查看更多内容
随时随地看视频慕课网APP