在php的多个dim数组中具有相同键的总值

时间:2011-10-12 18:01:01

标签: php

我有一个这样的数组:

$a = array(
    array('amount'=>10,'curr'=>'USD'),
    array('amount'=>20,'curr'=>'JPY'),
    array('amount'=>30,'curr'=>'BAT'),
    array('amount'=>50,'curr'=>'BAT'),
    array('amount'=>100,'curr'=>'USD')
    );

我想将所有相同的货币加在一起,然后像这样返回:

$total = array('BAT'=>80,
              'JPY'=>20,
              'USD'=>110
           )

1 个答案:

答案 0 :(得分:1)

$total = array();
foreach($a as $arr){
    if(!isset($total[$arr['curr']])){
        $total[$arr['curr']] = 0;
    }
    $total[$arr['curr']] += $arr['amount'];
}