沃梦达 / 编程问答 / php问题 / 正文

关联数组,对同一键的值求和

Associative array, sum values of the same key(关联数组,对同一键的值求和)

本文介绍了关联数组,对同一键的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个关联数组(用 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
        )

)

这篇关于关联数组,对同一键的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:关联数组,对同一键的值求和

基础教程推荐