php – 从数组中查找值的总和
发布时间:2020-12-13 21:54:16  所属栏目:PHP教程  来源:网络整理 
            导读:我有一个购物车表,并希望无论我在哪里状态= 1计算成本总和 id cost status1 10 12 10 12 10 12 10 2 我试过的代码是 $sql01 = "SELECT * FROM cart where status='1' ";$result01 = mysqli_query($con,$sql01);if (mysqli_num_rows($result01) 0) { while($r
                
                
                
            | 
 我有一个购物车表,并希望无论我在哪里状态= 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 解决方法
 一种方法是在SQL中计算总和,如另一个答案.如果要在PHP中执行此操作,可以将cost列添加到变量: 
  
  
  $total_cost = 0;
while ($row = mysqli_fetch_assoc($result01)) {
    $total_cost += $row['cost'];
}
echo "Result: $total_cost";(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! | 
