The input array:
[
[1 => 2],
[1 => 2],
[2 => 1],
[3 => 1],
]
I want this output:
[
[1 => 4],
[2 => 1],
[3 => 1],
]
The input array:
[
[1 => 2],
[1 => 2],
[2 => 1],
[3 => 1],
]
I want this output:
[
[1 => 4],
[2 => 1],
[3 => 1],
]
Seems like a good case for array_reduce():
$res = array_chunk(array_reduce($arr, function(&$current, $item) {
foreach ($item as $key => $value) {
if (!isset($current[$key])) {
$current[$key] = 0;
}
$current[$key] += $value;
}
return $current;
}, []), 1, true);
For the final result I'm using array_chunk(); it takes an array and creates single element sub arrays of each element.
By identifying unique groups and only pushing references into the result array, you can avoid needing to reindex the result after the loop. Demo
$result = [];
foreach ($array as $row) {
$k = key($row);
if (!isset($ref[$k])) {
$ref[$k] = 0;
$result[][$k] =& $ref[$k];
}
$ref[$k] += $row[$k];
}
var_export($result);
Output:
array (
0 =>
array (
1 => 4,
),
1 =>
array (
2 => 1,
),
2 =>
array (
3 => 1,
),
)