'Group values and sum keys in flat, associative array
Please help needed to solve output as array key sum and value by group.
My actual output :
$array = array(
'7'=>'15',
'20'=>'6',
'11'=>'9',
'14'=>'6',
'4'=>'15'
);
I need final array to sum of keys and group by value like :
$array = array('15' => 11, '6' => 34, '9' => 11);
Solution 1:[1]
Iterate the array and use each value as the keys in the result array. Use a null coalescing expression to fallback to zero when a specific value from the input array is encountered for the first time. As you iterate, simply add the input array's key to the result array's value "sum".
Code: (Demo)
$array = [
'7' => '15',
'20' => '6',
'11' => '9',
'14' => '6',
'4' => '15'
];
$result = [];
foreach ($array as $key => $value) {
$result[$value] = ($result[$value] ?? 0) + $key;
}
var_export($result);
Output:
array (
15 => 11,
6 => 34,
9 => 11,
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mickmackusa |
