如何获取数组中的值之和

时间:2016-09-24 20:19:35

标签: php mysql arrays

如何通过这里的方式添加我在每个数组中的值是我的代码我想在total_halin

中添加值
function generateReport($d1,$d2){
    $arr = array();
    $sql="SELECT dm.damage_qty,p.price,p.product_name,SUM(ps.pcs_bought) AS TOTAL_PCS FROM products p 
INNER JOIN sold_products ps
ON p.id = ps.product_id
LEFT JOIN damages dm
ON p.id = dm.product_id
WHERE ps.date_ordered BETWEEN '".$d1."' AND '".$d2."'
GROUP BY p.id";
    $result = Database::$conn->query($sql);
            if ($result->num_rows>0) {
            while ($row = $result->fetch_array()) {
                $i = new Product();
                $i->prodname = $row['product_name'];
                $i->total_pieces = $row['TOTAL_PCS'];
                $i->total_halin = $row['price'] * $row['TOTAL_PCS'];

                $i->damage = $row['damage_qty'];
                $arr[] = $i;
            }

        }
        return $arr;
 }

2 个答案:

答案 0 :(得分:0)

使用array_sum()返回数组中值的总和。

示例

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

结果就像 总和(a)= 20 sum(b)= 6.9

希望能回答你的问题

答案 1 :(得分:0)

$tot=0;
foeach($i->total_halin as $key=>$value)
{
    $tot+=$value;
}

$ tot是总和