How can I add all the columnar values by associative key? Note that key sets are dynamic.
Input array:
Arr
$sumArray = array();
foreach ($myArray as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
$sumArray[$id]+=$value;
}
}
print_r($sumArray);
Go through each item of the array and sum values to previous values if they exist, if not just assign the value.
<?php
$array =
[
[
'a'=>1,
'b'=>1,
'c'=>1,
],
[
'a'=>2,
'b'=>2,
],
[
'a'=>3,
'd'=>3,
]
];
$result = array_reduce($array, function($carry, $item) {
foreach($item as $k => $v)
$carry[$k] = $v + ($carry[$k] ?? 0);
return $carry;
}, []);
print_r($result);
Output:
Array
(
[a] => 6
[b] => 3
[c] => 1
[d] => 3
)
Or just loop through each sub array, and group the values for each column. Eventually summing them:
foreach($array as $subarray)
foreach($subarray as $key => $value)
$grouped[$key][] = $value;
$sums = array_map('array_sum', $grouped);