Group by one column and sum another column in a Laravel collection
I'm faily new to PHP & Laravel, and i've been given this task: I have a collection that looks like the one below:
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[id] => 1
[cardId] => 100
[cardQuantity] => 1234
)
[1] => stdClass Object
(
[id] => 2
[cardId] => 100
[cardQuantity] => 1234
)
[2] => stdClass Object
(
[id] => 7
[cardId] => 200
[cardQuantity] => 1234
)
[3] => stdClass Object
(
[id] => 8
[cardId] => 200
[cardQuantity] => 1234
)
)
)
and i have to filter each element based on the cardId
parameter, add (+) the cardQuantity
parameter, and then return new, distinct arrays that look like this:
(
[id] => 10
[cardId] => 100
[cardQuantity] => 2468
)
(
[id] => 11
[cardId] => 200
[cardQuantity] => 2468
)
How does one can achieve such a thing?
Solution 1:
You can have a vision about how to achieve this trying something like this:
$collection = collect([
['id' => 1, 'cardId' => 100, 'cardQuantity' => 1234],
['id' => 2, 'cardId' => 100, 'cardQuantity' => 1234],
['id' => 7, 'cardId' => 200, 'cardQuantity' => 1234],
['id' => 8, 'cardId' => 200, 'cardQuantity' => 1234],
]);
$unique = $collection->unique('cardId'); // returns a collection
$unique->transform(function ($item, $key) use ($collection) {
$id = $item['cardId'];
$item['cardQuantity'] = $collection->sum(function ($product) use ($id) {
if($product['cardId'] == $id){
return $product['cardQuantity'];
}
});
return $item;
});
return $unique->all();
The result this code returns is the unique collection transformed:
{
"0": {
"id": 1,
"cardId": 100,
"cardQuantity": 2468
},
"2": {
"id": 7,
"cardId": 200,
"cardQuantity": 2468
}
}
Basically, first we get the unique values by the cardId
key, after that we'll transform
the unique
collection, setting it's new values (the sum of the uniques). You can play and test more ways to do it. Hope you can find this useful.