关联数组,对同一键的值求和
所以我有这个关联数组(用 kint 完成转储)
So I have this associative array (dump done with kint)
而不是让键Conference
"重复 3 次.我只想拥有一次,然后将 3 个值合为一个,以便获得类似的结果:
Instead of having the key "Conference
" repeating 3 times. I want to have it just once and sum the 3 values into one in order to have something like:
会议:4534
对于所有其他重复的键也是如此..
And same thing for all other keys that are repeating..
有没有可以做到这一点的原生函数?
Is there a native function that can do that ?
推荐答案
你可以试试
$data = array(
0 => array(
'event' => 'Conference',
'budget' => 3700,
),
1 => array(
'event' => 'Conference',
'budget' => 500,
),
2 => array(
'event' => 'Showroom',
'budget' => 1000,
),
3 => array(
'event' => 'Mission Chez client',
'budget' => 2000,
),
4 => array(
'event' => 'Séminaire',
'budget' => 700,
),
5 => array(
'event' => 'Livraison',
'budget' => 4000,
),
6 => array(
'event' => 'Conference',
'budget' => 334,
),
);
$sum = array_reduce($data, function ($a, $b) {
isset($a[$b['event']]) ? $a[$b['event']]['budget'] += $b['budget'] : $a[$b['event']] = $b;
return $a;
});
print_r(array_values($sum));
输出
Array
(
[0] => Array
(
[event] => Conference
[budget] => 4534
)
[1] => Array
(
[event] => Showroom
[budget] => 1000
)
[2] => Array
(
[event] => Mission Chez client
[budget] => 2000
)
[3] => Array
(
[event] => Séminaire
[budget] => 700
)
[4] => Array
(
[event] => Livraison
[budget] => 4000
)
)
相关文章