Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zeroX's avatar
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.

0 likes
5 replies
bugsysha's avatar

Provide the input and expected output. Don't force people here who are trying to help to do unnecessary work.

SilenceBringer's avatar

@zerox something like

$posts->merge($pages)
	->sortBy('start')
	->groupBy(fn ($item) => $item->start->format('Y-m-d')) // assuming start is Carbon instance
	->map(fn ($dayData) => $dayData->groupBy('user_id'))
1 like
zeroX's avatar
Level 6

Hi SilenceBringer,

thank you. When i merge the two collections some data is getting removed, thats why i merged them with array_merge and converted them to arrays.

SilenceBringer's avatar
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
zeroX's avatar
Level 6

Amazing, thank you very much!

Please or to participate in this conversation.