doucong7963 2016-01-17 13:10
浏览 63
已采纳

PHP,Mysql avg while循环到JSON

I am having an issue understanding the proper use for a while loop in PHP. I am trying to get a JSON output like this ....

{"ratings":[{"id":"1","rating":"4.5"}},{"id":"2","rating":"3"}}]}

My php looks like this ...

<?php
$db_name="ratings";
require_once ('db_Connect.php');
mysql_select_db("$db_name")or die("cannot select DB");

$sql = "SELECT id, AVG(rating) FROM ratings GROUP BY id"; 

$result = mysql_query($sql) or die(mysql_error());
$result = mysql_fetch_array($result);

echo json_encode($result);
mysql_close($con);
?>

What the above php produces is ...

{"0":"1","id":"1","1":"1.5","AVG(rating)":"1.5"}

however, there are more results that should be displayed. And as you can see, this is not the anticipated results as there are only one row shown. And the format is not as desired.

My question is, where have I gone wrong with my code?

  • 写回答

1条回答 默认 最新

  • douhuitan5863 2016-01-17 13:18
    关注

    To produce a json like you want, you need to rearrange the result on array and finally encode in json format, like this:

    $arrayToFormat = array();
    while($row = mysql_fetch_array($result, MYSQL_NUM)){
          $arrayToFormat['ratings'][] = array('id' => $row[0], 'rating' => $row[1]);
    }
    echo json_encode($arrayToFormat);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line