PHP的和变量在while循环 [英] php sum variable in while loop

查看:77
本文介绍了PHP的和变量在while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在一段时间内求和"变量的值,这里是我的示例:

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'];
}

例如,如果我输入echo $price;,将输出以上代码:

The code above will output if I put echo $price; for example:

19 15 20 13 10

19 15 20 13 10

我想要类似:sum($price)array_sum($price)来计数while循环的所有结果.所以,我想算一下:19+15+20+13+10 = 77

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

我该如何使用php?

谢谢

推荐答案

只需在循环外初始化变量,例如:

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'];

这篇关于PHP的和变量在while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆