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

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
        )

)

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)