如何动态分组数组值并计算每组的总和?这是我目前的数组:
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 )
)
答案 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);