如何对多维数组值进行分组并获得每个组的总和?

时间:2014-07-30 03:43:20

标签: php

如何动态分组数组值并计算每组的总和?这是我目前的数组:

Array ( [0] => Array ( [source] => web [count] => 1 ) 
        [1] => Array ( [source] => web [count] => 1 ) 
        [2] => Array ( [source] => catalog [count] => 1 ) 
        [3] => Array ( [source] => magazine [count] => 1 ) 
        [4] => Array ( [source] => newspaper [count] => 1 ) 
        [5] => Array ( [source] => web [count] => 1 ) 
        [6] => Array ( [source] => newspaper [count] => 1 ) 
        [7] => Array ( [source] => web [count] => 1
)

这是我想要实现的目标:

Array ( [0] => Array ( [source] => web [count] => 4 ) 
        [1] => Array ( [source] => catalog [count] => 1 ) 
        [2] => Array ( [source] => magazine [count] => 1 ) 
        [3] => Array ( [source] => newspaper [count] => 2 ) 
)

1 个答案:

答案 0 :(得分:1)

我将继续这样做:

<pre><?php

$arr = array ( array ( 'source' => 'web', 'count' => 1 ), 
               array ( 'source' => 'web', 'count' => 1 ), 
               array ( 'source' => 'catalog', 'count' => 1 ), 
               array ( 'source' => 'magazine', 'count' => 1 ), 
               array ( 'source' => 'newspaper', 'count' => 1 ), 
               array ( 'source' => 'web', 'count' => 1 ), 
               array ( 'source' => 'newspaper', 'count' => 1 ), 
               array ( 'source' => 'web', 'count' => 1)
      );

$temp = array();
foreach ($arr as $v) {
    $temp[$v['source']] += $v['count'];
}

$result = array();
foreach ($temp as $k => $v) {
    $result[] = array( 'source' => $k, 'count' => $v );
}
unset($temp);

print_r($result);