如何对分组总和值的值求和PHP的MySQL

时间:2019-07-16 02:06:19

标签: php mysql json

以下PHP脚本将两个表连接在一起,并根据查询显示JSON。

<?php

$con=mysqli_connect("localhost","username","password","dbName");


if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


$sql =  "SELECT User, SUM(Price) as sumValue 
FROM Table1
LEFT JOIN Table2 USING(Product)
GROUP BY User";

if ($result = mysqli_query($con, $sql))
{

    $resultArray = array();
    $tempArray = array();

    while($row = $result->fetch_object())
    {
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    echo json_encode($resultArray);
}

mysqli_close($con);


?>

由于用户的查询组,每个用户显示其自己的sumValue。

我得到以下JSON结果:

[{"user":"Jack","sumValue":"4.50"},
{"user":"Jake","sumValue":" 4.00 "},{"user":"Mary","sumValue":" 8.50 "}] 

如何添加所有sumValue的总和,并将其显示在JSON的末尾,如:

[{"user":"Jack","sumValue":"4.50"},
{"user":"Jake","sumValue":" 4.00 "},{"user":"Mary","sumValue":" 8.50 "}, 
{"sumTotal": "17.00"}]

3 个答案:

答案 0 :(得分:0)

未经测试,但我认为您可以再添加一个变量,将其添加到循环中,然后在执行之后和json创建之前追加。

$tempArray = array();
$sum = 0;
while($row = $result->fetch_object())
{
    $tempArray = $row;
    array_push($resultArray, $tempArray);
    $sum += $tempArray['sumValue'];
}
array_push($resultArray, array('sumTotal' => $sum); 
echo json_encode($resultArray);

答案 1 :(得分:0)

将它们简单地加到循环中。

<?php
$con=mysqli_connect("localhost","username","password","dbName");


if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


$sql =  "SELECT User, SUM(Price) as      sumValue 
FROM Table1
LEFT JOIN Table2 USING(Product)
GROUP BY User";

if ($result = mysqli_query($con, $sql))
{

    $resultArray = array();
    $tempArray = array();

    // you want an array of objects, so create an object to sum the sub totals
    $total = new stdClass;
    $total->sumTotal = 0;

    while($row = $result->fetch_object())
    {
        $tempArray = $row;
        array_push($resultArray, $tempArray);

        // $resultArray[] = $row;  // shorter... $tempArray unneeded.

        $total->sumTotal += $row->sumValue;

        // better way to do it:
        // $total->sumTotal = bcadd($total->sumTotal, $row->sumValue);
    }

    $resultArray[] = $total;
    echo json_encode($resultArray);
}

mysqli_close($con);


?>

但是,有一个巨大的警告:浮点数学。

如果精度很重要(例如货币),则需要使用bcmath函数

答案 2 :(得分:0)

尝试一下:

if ($result = mysqli_query($con, $sql))
    {
        $resultArray = array();
        $total = 0;

        while($row = $result->fetch_object())
        {
            array_push($resultArray, $row);
            $total += $row->sumValue;
        }

        array_push($resultArray, array('sumTotal' => $total));
        echo json_encode($resultArray);
    }