Provide the input and expected output. Don't force people here who are trying to help to do unnecessary work.
Sep 8, 2021
5
Level 6
Merge two collections, sort by date, group by day and group by user id
Hi,
i have two collections that i want to merge, sort by date, group by day and then group by user id.
So far i can merge, sort by date and group by day but can't figure out how to also group by user id.
What i want to achieve is a list by day and user sorted by date and time.
// Merge collections and sort by start time
$merged = array_merge($posts->toArray(), $pages->toArray());
usort($merged, fn($a, $b) => strtotime($a['start']) - strtotime($b['start']));
// Group the array by day
$groupedByDay = array();
foreach ($merged as $key => $item) {
$groupedByDay[date('Y-m-d', strtotime($item['start']))][$key] = $item;
}
ksort($groupedByDay, SORT_NUMERIC);
return $groupedByDay;
The current output is:
{
"2021-09-06": [
{
"user_id": 54,
"start": "2021-09-06 05:00:00",
"end": "2021-09-06 06:00:00"
},
{
"user_id": 54,
"start": "2021-09-06 06:00:00",
"end": "2021-09-06 07:00:00"
},
{
"user_id": 54,
"start": "2021-09-06 08:00:00",
"end": "2021-09-06 09:00:00"
},
{
"user_id": 54,
"start": "2021-09-06 10:00:00",
"end": "2021-09-06 11:00:00"
},
{
"user_id": 52,
"start": "2021-09-06 11:00:00",
"end": "2021-09-06 12:00:00"
}
],
"2021-09-07": {
"5": {
"user_id": 52,
"start": "2021-09-07 13:00:00",
"end": "2021-09-07 14:00:00"
}
}
}
Thank you in advance.
Level 55
@zerox not sure I understand, but
collect($posts->toArray(), $pages->toArray())
->sortBy('start')
->groupBy(fn ($item) => $item['start']) // perform necessary manipulations with start
->map(fn ($dayData) => $dayData->groupBy('user_id'))
1 like
Please or to participate in this conversation.