本文介绍了如何将数组转换为json对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将值推入数组,结果就像
I am trying to push values in an array and it comes like
[{"Monday":"11:30"},{"Monday":"12:00"},{"Monday":"23:00"},{"Tuesday":"11:30"},{"Tuesday":"12:00"},{"Tuesday":"23:00"}]
但是我希望它成为像这样的对象
But I want it to be an object like
{
"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;
推荐答案
您可以使用mapToGroups
获取要求的格式.但是我不知道你的表结构,所以我得到了这些;
You may use mapToGroups
to get in the requested format. But i don't know your table structure so i got these;
[{"Monday":"11:30"},{"Monday":"12:00"},{"Monday":"23:00"},{"Tuesday":"11:30"},{"Tuesday":"12:00"},{"Tuesday":"23:00"}]
放入集合(假设您雄辩的集合返回了这样的内容)
put into the collection (assuming your eloquent collection returns like that)
$timings = collect([
["Monday" => "11:30"],
["Monday" => "12:00"],
["Monday" => "23:00"],
["Tuesday" => "11:30"],
["Tuesday" => "12:00"],
["Tuesday" => "23:00"]
]);
return $timings->mapToGroups(function ($item) {
$day = array_key_first($item);
return [$day => $item[$day]];
});
将其打印出来;
{
"Monday": [
"11:30",
"12:00",
"23:00"
],
"Tuesday": [
"11:30",
"12:00",
"23:00"
]
}
(您在网上发布的数组与此处使用的数组相同,并且与我用于解决方案的函数相同)
(the same array you posted in online used here + same function i used for solution)
$days = ["Monday", "Monday"];
$time = ["11:30", "12:30"];
$doctor_timings = [];
for ($i = 0; $i < sizeof($days); $i++) {
$day_id = $days[$i];
$time_id = $time[$i];
array_push($doctor_timings, [$day_id => $time_id]);
}
return collect($doctor_timings)->mapToGroups(function ($item) {
$day = array_key_first($item);
return [$day => $item[$day]];
});
可打印
{"Monday":["11:30","12:30"]}
这篇关于如何将数组转换为json对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!