I am working with collections in Laravel and I have the following problem, I need to join objects that have the same key inside the array, at the same time obtain the total sum of one of its keys, this is a summary of my collection:
[
{
"cta_debe": 20,
"total": "2000.00",
},
{
"cta_debe": 22,
"total": "3600.00",
},
{
"cta_debe": 22,
"total": "1000.00",
},
{
"cta_haber": 10,
"total": "5000.00",
},
{
"cta_haber": 10,
"total": "4000.00",
}
]
where I have several objects that have the keys "cta_debe" and "cta_haber" with the same value, then I would like to join all the equal objects into one, in addition to adding the total column, this is an example of how I expect the collection to be :
[
{
"cta_debe": 20,
"total": "2000.00",
},
{
"cta_debe": 22,
"total": "4600.00",
},
{
"cta_haber": 10,
"total": "9000.00",
},
]
any idea how i could do this?
CodePudding user response:
You can use collection methods:
$result = collect($myArray)->groupBy('cta_debe')->map(function ($group, $id) {
return [
'cta_debe' => $id,
'total' => collect($group)->sum('total')
];
});
CodePudding user response:
Preparing data as yours.
$data = collect([
collect(['cta_debe' => 20, 'total' => '2000.00']),
collect(['cta_debe' => 22, 'total' => '3600.00']),
collect(['cta_debe' => 22, 'total' => '1000.00']),
collect(['cta_haber' => 10, 'total' => '5000.00']),
collect(['cta_haber' => 10, 'total' => '4000.00']),
]);
Your solution start from here..
$groupedData = $data->groupBy(fn ($item, $key) => $item->keys()->first());
$newData = collect([]);
foreach ($groupedData as $groupKey => $groupValue) {
$againGroupedData = $groupValue->groupBy($groupKey);
foreach ($againGroupedData as $key => $value) {
$newData->push(
collect([
$groupKey => $key,
'total' => $value->map(fn ($item) => (float) $item['total'])->sum()
])
);
}
}
$finalData = $newData->all();
Output: