0

How would i get the sum of the totals for the following PHP Array?

I am running this: print_r($myArray);

Array
(
    [0] => Array
        (
            [total] => 100.0000
        )

    [1] => Array
        (
            [total] => 100.0000
        )

    [2] => Array
        (
            [total] => 689.5000
        )
)
4

1 回答 1

3

You can use array_reduce

$total = array_reduce($array, function($a,$b) {return $a + $b['total'];});
var_dump($total);

You can use array_map

$total = 0;
array_map(function($v) use(&$total) { $total += $v['total'];},$array);
var_dump($total);

Your Just loop

for($i = 0, $total = 0; $i < count($array); $i ++) {
    $total += $array[$i]['total'];
}
var_dump($total);

Output

float 889.5
于 2012-10-19T01:24:03.133 回答