简体   繁体   English

php while变量在while循环中

[英]php sum variable in while loop

I have to "sum" variable's values in while, here us my example : 我必须“汇总”变量的值,而这里是我的例子:

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

The code above will output if I put echo $price; 如果我把echo $price;上面的代码将输出echo $price; for example: 例如:

19 15 20 13 10 19 15 20 13 10

I want something like : sum($price) or array_sum($price) to count all the results of while loop. 我想要像: sum($price)array_sum($price)来计算while循环的所有结果。 So, that i want to count: 19+15+20+13+10 = 77 所以,我想算一下: 19+15+20+13+10 = 77

How can I do it with php? 我怎么能用PHP做到这一点?

Thanks 谢谢

Simply initialize a variable outside your loop for example: 只需在循环外初始化变量,例如:

$total_price = 0;

and increment this number inside your loop: 并在循环中增加此数字:

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

eg 例如

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

Or - if all you want from the query is the total - you can do it "within" the sql query. 或者 - 如果你想从查询中得到的只是总数 - 你可以在sql查询中“执行”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM