php while循环中的php sum变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10329535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php sum variable in while loop
提问by user1358069
I have to "sum" variable's values in while, here us my example :
我必须在 while 中“求和”变量的值,这里是我的示例:
while($row = mysql_fetch_array($result)){
$price= $row['price'] * $row['order_q'];
}
The code above will output if I put echo $price;for example:
如果我echo $price;输入例如,上面的代码将输出:
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. So, that i want to count: 19+15+20+13+10 = 77
我想要类似 :sum($price)或array_sum($price)计算 while 循环的所有结果。所以,我想计算:19+15+20+13+10 = 77
How can I do it with php?
我怎样才能用 php 做到这一点?
Thanks
谢谢
回答by Salman A
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'];
回答by VolkerK
e.g.
例如
$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 ...

