按数组计算数组

时间:2013-01-01 12:06:53

标签: php arrays sum grouping

是否可以按数组计算数组?

例如,按每个[num]计算[price][group]的总和。

Array
(
    [0] => Array
        (
            [group] => Apple
            [num] => 5
            [price] => 10
        )

    [1] => Array
        (
            [group] => Apple
            [num] => 2
            [price] => 8
        )

    [2] => Array
        (
            [group] => Orange
            [num] => 4
            [price] => 6
        )

    [3] => Array
        (
            [group] => Orange
            [num] => 12
            [price] => 24
        )

)

结果如下:

Array
(
    [0] => Array
        (
            [group] => Apple
            [num] => 7
            [price] => 18
        )

    [1] => Array
        (
            [group] => Orange
            [num] => 16
            [price] => 30
        )
)

2 个答案:

答案 0 :(得分:2)

简单循环和关联数组将完成这项工作:

$result = Array();
foreach($array as $row) {
   if(!isset($result[ $row['group'] ])) {
       $result[ $row['group'] ] = $row;
       continue ;
   }
   $result[ $row['group'] ]['num'] += $row['num'];
   $result[ $row['group'] ]['price'] += $row['price'];
}
$result = array_values($result);

答案 1 :(得分:1)

使用array_reduce()

$reduced = array_reduce($array, function(&$result, $item){
    $result[$item['group']]['num'] += $item['num'];
    $result[$item['group']]['price'] += $item['price'];
    return $result;
});