我如何在PHP中使用JSON结果进行计算

时间:2016-05-06 10:40:49

标签: php json

我想在一些计算中使用json结果,但无论我尝试它都没有用。

<?php 

//product id
$gp_id=$_GET['gp_id'];

//Importing the database connection 
require_once('dbConnect.php');

    $sql2 = "SELECT sum(rating_score) AS total_rate ,count(consumer_id) AS consumer
            FROM productrate 
            WHERE gp_id='$gp_id'";

    //Getting result 
    $result = mysql_query($sql2); 

    //Adding results to an array 
    $res = array(); 

    while($row = mysql_fetch_array($result))
    {
        array_push($res, array(
          // "gp_id"=>$row['gp_id'],
            "total_rate"=>$row['total_rate'],
            "consumer"=>$row['consumer']
            )
); }

    //Displaying the array in json format 
    $objJson=json_encode($res);
    echo $objJson;

//calculate avg rate of specific product
$avg_rate =  (int)"total_rate" /  (int)"consumer";
echo  $avg_rate ;

?>

正如你在最后看到的那样,我尝试做一些计算,但它没有用。

这是输出...... [{&#34; Total_Rate的&#34;:&#34; 18&#34;&#34;消费者&#34;:&#34; 4&#34;}] 警告:在第33行的C:\ xampp \ htdocs \ totalrate \ highRate.php中除以零

3 个答案:

答案 0 :(得分:0)

$objJson=json_encode($res);生成json字符串。例如'{"a":1,"b":2,"c":3,"d":4,"e":5}'。你不能像变量一样使用它。它的字符串。

答案 1 :(得分:0)

$avg_rate = "total_rate" / "consumer";

看起来你试图用另一个字符串分割字符串。 请尝试使用数组元素,例如:

$avg_rate = $res["total_rate"] / $res["consumer"];

答案 2 :(得分:0)

最后我解决了这个问题...

 //product id
$gp_id=$_GET['gp_id'];

//Importing the database connection 
 require_once('dbConnect.php');

$sql2 = "SELECT sum(rating_score) AS total_rate ,count(consumer_id) AS consumer
        FROM productrate 
        WHERE gp_id='$gp_id'";
//Getting result 
$result = mysql_query($sql2) or die(mysql_error());

//Adding results to an array 
$res = array(); 

while($row = mysql_fetch_array($result))
{
        array_push($res, array(
        "avg_rate"=>$row['total_rate']/ $row['consumer'],
        "total_rate"=>$row['total_rate'],
        "consumer"=>$row['consumer']
        )
     ); }

//Displaying the array in json format 
$objJson=json_encode($res);
echo $objJson;
 ?>