Ad
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?
Ad
Answer
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.
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad