在 while 循环中对 PHP 变量求和

7

我需要在while循环中对变量的值进行“求和”,以下是我的示例:

while($row = mysql_fetch_array($result)){
  $price= $row['price'] * $row['order_q'];
}

上面的代码将输出如果我放置例如echo $price;

19 15 20 13 10

我想要像 sum($price) 或者 array_sum($price) 这样的东西来计算 while 循环的所有结果。所以,我想要计算:19+15+20+13+10 = 77 如何使用 PHP 实现?
谢谢。

为什么你不使用array_sum()函数? - Chandresh M
2个回答

19

只需在循环外初始化一个变量即可,例如:

$total_price = 0;

并在您的循环内增加此数字:

$total_price += $row['price'] * $row['order_q'];

非常感谢,这就是我想要做的 ^^ - user1358069

13

例如。

$total = 0;
while($row = mysql_fetch_array($result)){
  $price= $row['price'] * $row['order_q'];
  $total += $price;
}
echo 'total: ', $total;

或者,如果您只想从查询中获取总数,您可以在SQL查询内部完成。

SELECT Sum(price*order_q) as total FROM ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接