PHP - 用相同的键对值求和 [英] PHP - sum values with the same key

查看:39
本文介绍了PHP - 用相同的键对值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将每种不同颜色的val"字段与相同颜色"相加的最佳方法是什么:

What is the best way to sum the 'val' field with the same 'color' for each different color:

Array
(
    [0] => Array
        (
            [color]=> "red"
            [val]=> 4
        )

    [1] => Array
        (
            [color]=> "green"
            [val]=> 3
        )

    [2] => Array
        (
            [color]=> "blue"
            [val]=> 1
        )

    [3] => Array
        (
            [color]=> "green"
            [val]=> 6
        )

    [4] => Array
        (
            [color]=> "blue"
            [val]=> 2
        )
)

期望结果:红色:4;绿色:9;蓝色:3.

Desired result : red: 4; green: 9; blue: 3.

问候,埃利奥·费尔南德斯

Regards, Elio Fernandes

推荐答案

我会这样做,使用 foreach 循环:

I would do it this way, with a foreach loop:

$temp = [];
foreach($arr as $value) {
    //check if color exists in the temp array
    if(!array_key_exists($value['color'], $temp)) {
        //if it does not exist, create it with a value of 0
        $temp[$value['color']] = 0;
    }
    //Add up the values from each color
    $temp[$value['color']] += $value['val'];
}

这篇关于PHP - 用相同的键对值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆