多数组 - 计算元素的值

时间:2014-10-31 13:13:46

标签: php arrays

我有这个数组:

Array(
[0] => Array(
[id] => 1,
[value] => 100
)
[1] => Array(
[id] => 1,
[value] => 200
)
[2] => Array(
[id] => 1,
[value] = 300
)
[3] => Array(
[id] => 2,
[value] = 100
)
[4] => Array(
[id] => 2.
[value] => 200
)
)

如何计算具有相同[id]的元素的[值]之和,并将其放入数组中:

Array(
[1] => 600,
[2] => 300
)

? 谢谢!

1 个答案:

答案 0 :(得分:0)

$array=array(array('id'=>1,'value'=>100),array('id' => 1,'value' => 200),array('id' => 1,'value' => 300),array('id' => 2,'value' => 100),array('id' => 2,'value'=> 200));

$res=array();
foreach($array as $a)
{
    if(array_key_exists ($a['id'],$res ))
    {
        $res[$a['id']]+=$a['value'];
    }
    else
    {
        $res[$a['id']]=$a['value'];
    }
}
print_r($res);

<强>输出

 Array ( [1] => 600 [2] => 300 )