所以我有这个关联数组(使用kint完成转储)
d
而不是让关键“会议”重复3次.我想只让它一次,并将3个值合并为一个,以便有类似的东西:
会议:4534
对于重复的所有其他键也一样
是否有可以做到这一点的本机功能?
解决方法:
你可以试试
$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
)
)
标签:php,arrays,sum,associative-array
来源: https://codeday.me/bug/20190918/1810972.html