如何计算同一数组中总密钥的总和

时间:2017-10-06 23:31:29

标签: php arrays foreach

我需要计算包含4个不同子数组的以下数组中的总键

Array
(
    [0] => Array
        (
            [total] => 4.2
            [sku] => 4321
        )

    [1] => Array
        (
            [total] => 2
            [sku] => 2456
        )

    [2] => Array
        (
            [total] => 3
            [sku] => 2245
        )

    [3] => Array
        (
            [total] => 1.5
            [sku] => 2674
        )

)

我是直接使用mysql计算它,但我更喜欢使用php

$sql = "SELECT SUM(CAST(IFNULL(total,0) AS DECIMAL(10,2))) FROM trans WHERE trans.userid = :userid";

所以总数必须与查询

的格式相同
  

10.70

4 个答案:

答案 0 :(得分:4)

您可以遍历数组,随意添加,然后使用number_format()进行格式化,或使用array_column()提取“总计”,并使用array_sum()添加它们,并再次使用number_format()sprintf()格式化它们。

echo number_format(array_sum(array_column($array, 'total')), 2);

答案 1 :(得分:1)

我猜是这样的: -

  $array = Array
    (
        [0] => Array
            (
                [total] => 4.2
                [sku] => 4321
            )

        [1] => Array
            (
                [total] => 2
                [sku] => 2456
            )

        [2] => Array
            (
                [total] => 3
                [sku] => 2245
            )

        [3] => Array
            (
                [total] => 1.5
                [sku] => 2674
            )

    );
   $total = 0;

   foreach ($array as $key => $value) {
        $total += $value['total'];
   }

   print_r($total);

答案 2 :(得分:0)

你可以迭代你的数组并总结所有的值,如:

<?php 
$array = array(
    array(
    'total' => 4.2,
    'sku' => 4321
    ),
    array(
    'total' => 2,
    'sku' => 2456
    ),
    array(
    'total' => 3,
    'sku' => 2245
    ),
    array(
    'total' => 1.5,
    'sku' => 2674
    ),
);


$result = array('total' => 0,'sku' => 0);
foreach($array as $key => $value) {
    $result['total'] += $value['total'];
    $result['sku'] += $value['sku'];
}
var_dump($result);

结果:array(2){[“total”] =&gt; float(10.7)[“sku”] =&gt; int(11696)}

单个总和输出

echo $result['total'];

答案 3 :(得分:0)

您也可以尝试array_walk_recursive()这样的https://eval.in/875555

$input = [your_2d_array_goes_here];
$final = array();    
array_walk_recursive($input, function($item, $key) use (&$final){
    $final[$key] = isset($final[$key]) ?  $item + $final[$key] : $item;
});

print '<pre>';
print_r($final);
print '</pre>';
print $final['total'];
?>