I have an array to be summed by column(s)
Array (
0 => [
[category] => Tools, furniture & fixtures
[period] => 2022-07
[depreciation] => 100
],
1 => [
[category] => Tools, furniture & fixtures
[period] => 2022-07
[depreciation] => 50
],
2 => [
[category] => Machines
[period] => 2022-07
[depreciation] => 25
],
3 => [
[category] => Machines
[period] => 2022-07
[depreciation] => 75
],
4 => [
[category] => Machines
[period] => 2022-08
[depreciation] => 200
]
)
I want to sum depreciation column by combination of category and period column, something like :
Array (
0 => [
[category] => Tools, furniture & fixtures
[period] => 2022-07
[depreciation] => 150
],
1 => [
[category] => Machines
[period] => 2022-07
[depreciation] => 100
],
2 => [
[category] => Machines
[period] => 2022-08
[depreciation] => 200
]
)
I tried to used to utilize this function to do this IF only one column as the parameter/key, and no idea if it have to be more than one column (category and period) :
$itemsSummed = [];
foreach ($depreciations as $item) {
if (array_key_exists($item['category'], $itemsSummed)) {
$itemsSummed[$item['category']]['depreciation'] += $item['depreciation'];
} else {
$itemsSummed[$item['category']] = $item;
}
}
$itemsSummed = array_values($itemsSummed);
How can i achieve this ?