1

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

例如,计算 和[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
        )
)
4

2 回答 2

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);
于 2013-01-01T12:10:18.673 回答
1

使用array_reduce()

$reduced = array_reduce($array, function(&$result, $item){
    $result[$item['group']]['num'] += $item['num'];
    $result[$item['group']]['price'] += $item['price'];
    return $result;
});
于 2013-01-01T12:23:42.947 回答