foreach中计算列的总和

时间:2014-12-24 09:13:10

标签: php mysql

我有一个mysql表

service_charges

id service_name service_charges 

我使用像

这样的mysql查询
select service_name service, service_charges,count(service_name)as unit 
from service charges group_by service

在php文件中我正在使用

foreach(services as service){
echo $service['service'];
echo $service['service_charges'];
echo $service['unit'];
$service_charges_total = (($service['service_charges'])*($service['unit']));
echo $sevice_charges_total;
}

我得到的结果如下: enter image description here

现在如何获得$ service_charges_total(金额列)的总金额,即我想要总计4200 + 1200 + 350 = 5750。

感谢。

4 个答案:

答案 0 :(得分:1)

你可以在你的函数这样做

$total=0;
foreach(services as service)
{
   echo $service['service'];
   echo $service['service_charges'];
   echo $service['unit'];
   $service_charges_total = (($service['service_charges'])*($service['unit']));
   echo $sevice_charges_total;
   $total+=$sevice_charges_total;
}
echo $total;

答案 1 :(得分:1)

select service_name as service, 
       service_charges,
       count(service_name) as unit,
       (select sum(service_charges) from service) as total_amount
from service as charges 
group_by service, 
         service_charges

答案 2 :(得分:0)

SELECT sum(Amount) from service_charges;

答案 3 :(得分:0)

我希望这对你有用

将金额值存储在数组中,然后使用array_sum()

$service_charges_total = (($service['service_charges'])*($service['unit']));
$array[]=$service_charges_total;
$total_sum=array_sum($array);
echo $total_sum;