从数组中找到值的总和

时间:2015-07-07 07:28:43

标签: php mysql sql arrays mysqli

我有一个购物车表,希望无论我在哪里状态= 1

计算成本总和
id  cost   status
1   10     1
2   10     1
2   10     1
2   10     2

我尝试的代码是

$sql01 = "SELECT * FROM cart where status='1' ";

$result01 = mysqli_query($con, $sql01);
if (mysqli_num_rows($result01) > 0) 
    {
        while($row = mysqli_fetch_assoc($result01)) 
            {
                $price = array_sum($row);
                echo "sum of cod:"; echo $price;
                echo "<br>";
            }
    }

我得到的结果是

10
10
10

应该是

的结果
30

5 个答案:

答案 0 :(得分:4)

一种方法是在SQL中计算总和,如另一个答案。如果要在PHP中执行此操作,可以将cost列添加到变量:

$total_cost = 0;
while ($row = mysqli_fetch_assoc($result01)) {
    $total_cost += $row['cost'];
}
echo "Result: $total_cost";

答案 1 :(得分:1)

您正在计算每一行的总和。相反,你应该试试这个:

$sql01 = "SELECT * FROM cart where status='1'";

$result01 = mysqli_query($con, $sql01);
$cost_array = array();
if (mysqli_num_rows($result01) > 0) 
    {
        while($row = mysqli_fetch_assoc($result01)) 
            $cost_array[] = $row['cost'];
    }
echo "Result: ".array_sum($cost_array);

或者(更好!)以这种方式优化您的MySQL查询:

SELECT sum(cost) finalprice FROM cart where status='1' GROUP BY status

现在,您可以使用$row['finalprice']访问您的金额。

答案 2 :(得分:1)

这是您的查询:

SELECT sum(cost) as price FROM cart WHERE status='1' GROUP BY status

PHP代码:

$sql01 = 'SELECT sum(cost) as price FROM cart WHERE status='1' GROUP BY status'
$result01 = mysqli_query($con, $sql01);
if (mysqli_num_rows($result01) > 0) 
    {
        while($row = mysqli_fetch_assoc($result01)) 
            {
                echo 'sum of cod:' . $row['price'] . '<br>';
            }
    }

详细了解GROUP BY:

  

https://dev.mysql.com/doc/refman/5.0/en/group-by-functions-and-modifiers.html

答案 3 :(得分:1)

它比你的代码更容易:在SQL中你应该使用

"Select sum(cost) from cart where status = '1';"

答案 4 :(得分:0)

使用此:

SELECT sum(cost) FROM cart group by status having status='1'