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

Kris01's avatar

Group Collection by month

Hi guys,

I have a json of transactions, in each transaction there is amount and date. I want to group all the results by month. For example I want a result like this:

{
		month: 22-11       (november)
		amount: x$
}
0 likes
5 replies
Sinnbeck's avatar

How is the format for January, February etc? 1 or 01?

Sinnbeck's avatar

@Kris01 ah ok so the example is the final output? So amount is a sum of all amounts that month?

How does the input look?

Kris01's avatar

@Sinnbeck The input looks like this:

array => {
	0 => {
			amount: 5000 usd
			date: 2022-07-19T21:18:38+0000
	}
	1 => {
			amount: 300 usd
			date: 2022-07-20T21:18:38+0000
	}
}

and I would like to sum up the amount and group them by month, to have a final result of: february the total amount was x usd march the toal amount was x usd

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@Kris01 ok something like this

$x = collect($data)->map(function($item) {
     $item['amount'] = str_replace(' usd', '', $item['amount']) ;
     return $item;
})->groupBy(function ($item) {
    return \Carbon\Carbon::parse($item['date'])->format('Y m');
})->map->sum('amount')
->map(function ($sum, $date) {
    return [
        'month' => $date, 
        'amount' => $sum
  ];
});

Please or to participate in this conversation.