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
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]];
});
which prints these;
{
"Monday": [
"11:30",
"12:00",
"23:00"
],
"Tuesday": [
"11:30",
"12:00",
"23:00"
]
}
Edit: (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]];
});
which prints
{"Monday":["11:30","12:30"]}