如何在PHP中对数组中的分组元素求和

时间:2017-11-22 04:20:13

标签: php arrays

假设我在PHP中有这个数组

Array(
    [0] => Array
        (
            [DLVRD] => 2
            [FAILED] => 1
            [REJECT] => 4
            [QUEUED] => 5
        )

    [1] => Array
        (
            [DLVRD] => 5
            [FAILED] => 0
            [REJECT] => 3
            [QUEUED] => 2
        )

    [2] => Array
        (
            [DLVRD] => 3
            [FAILED] => 0
            [REJECT] => 1
            [QUEUED] => 3
        )
)

我想做的就是得到像这样的结果

Array
(
    [DLVRD] => 10
    [FAILED] => 1
    [OTHERS] => 8
)

目前我的PHP代码是这样的:

foreach($GetTelcosRevenue as $telco) {        
            if($telco['dr_detail'] == 'DLVRD') {
                $TelcoRevenue .="DLVRD:".$telco['TheTraffics'].",";
            }
            else if($telco['dr_detail'] == 'FAILED') {
                $TelcoRevenue .="FAILED:".$telco['TheTraffics'].",";
            }
            else {
                ?????
            }
        }
    }

我试图把$ Others + = $ telco ['TheTraffics']和其他黑客但我仍然得错了结果。谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

你可以这样做:

$sum = array();

foreach ($array as $k=>$sub) {  // $array is your question array
  foreach ($sub as $id=>$value) {
    $sum[$id]+=$value;
  }
}

print_r($sum);