php中的数组总和

时间:2013-07-02 05:57:29

标签: php arrays function

我有这个数组

[2] => Array
        (
            [0] => 1160
            [1] => 1155
            [2] => 06/26/2013
            [3] => 32.99
        )

    [3] => Array
        (
            [0] => 1160
            [1] => 1155
            [2] => 06/26/2013
            [3] => 0.00
        )

    [4] => Array
        (
            [0] => 1160
            [1] => 1155
            [2] => 06/24/2013
            [3] => 20.99
        )

    [5] => Array
        (
            [0] => 1160
            [1] => 1155
            [2] => 06/24/2013
            [3] => 10.78
        )

问题::我希望基于“oder_id”数组[0]相同的值我要求“数量”数组的总和[3]

帮我解决一下这个

2 个答案:

答案 0 :(得分:2)

$results = array();

foreach($data as $val){
     if(!array_key_exists($val[0], $results)){
         $results[$val[0]] = 0;
     }
     $results[$val[0]]+= $val[3];
}

此结果后,$ results将包含从order_id

键入的总计

答案 1 :(得分:2)

您可以像这样使用foreach

$sum = 0;
foreach ($rows as $row) {
    $sum += $row[0];
}