[英]Group values and sum keys in flat, associative array
Please help needed to solve output as array key sum and value by group.请帮助解决 output 作为数组键和和值按组。
My actual output:我的实际 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);
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.当第一次遇到来自输入数组的特定值时,使用 null 合并表达式回退到零。 As you iterate, simply add the input array's key to the result array's value "sum".迭代时,只需将输入数组的键添加到结果数组的值“sum”。
$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: Output:
array (
15 => 11,
6 => 34,
9 => 11,
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.