I'm using the Laravel groupBy method to format my data and group them into periods, however, I'd like to change how I return my results. Rather than using the created_at as the key for an array item, I don't want there to be a key, and instead, just move that key into the returned result instead...
The following code will return:
"results": [
{
"2021-03-04": {
"event_category": "category",
"event_action": "action",
"event_count": "544",
"period_from": "2021-03-04 00:00:00",
"period_to": "2021-03-04 10:30:02",
"created_at": "2021-03-04 10:30:06"
},
"2021-03-03": {
"event_category": "category",
"event_action": "action",
"event_count": "5337",
"period_from": "2021-03-03 00:00:00",
"period_to": "2021-03-03 23:57:03",
"created_at": "2021-03-03 23:57:08"
}
}
]
Here's how that looks
$res = DB::table('my_table')
->select('event_category', 'event_action', 'event_count', 'period_from', 'period_to', 'created_at')
->where([["event_category", "category"], ["event_action", "action"], ["period_from", ">=", "2021-03-01"], ["period_to", "<=", "2021-03-04 22:00:00"]])
->orderBy('created_at, 'desc')
->get();
$results = $res->groupBy(function ($item, $key) use ($findable) {
$date = Carbon::parse($item->created_at);
return $date->format($findable['groupByFormat']);
});
$results = $results->map(function ($item, $key) {
return $item[0];
});
$res = $results;
I'd like to return...
"results": [
[
"event_category": "category",
"event_action": "action",
"event_count": "544",
"period_from": "2021-03-04 00:00:00",
"period_to": "2021-03-04 10:30:02",
"created_at": "2021-03-04 10:30:06",
"new_created_at": '2021-03-04'
],
[
"event_category": "category",
"event_action": "action",
"event_count": "5337",
"period_from": "2021-03-03 00:00:00",
"period_to": "2021-03-03 23:57:03",
"created_at": "2021-03-03 23:57:08",
"new_created_at": '2021-03-03'
]
]
I've tried removing my initial map, but not sure how to achieve such format whilst remaining the grouping