douzhun8615 2014-04-04 18:51
浏览 36
已采纳

创建没有多个SQL查询的JSON对象(PHP)

I'm trying to create this kind of JSON object by using MySQL/ PHP.

[ 
{
  "hours":0
  "vulnerability":867
  "file":166
  "virus":59
}, 
{
  "hours":1
  "vulnerability":400
  "file":14
  "virus":40
}, 
]

I'm trying to reduce the amount of queries sent to the server as my db scales quite large. My query returns these results:

SQL data

So while looping through the data I'm getting this kind of JSON returned:

{
  "hours":0
  "vulnerability":867
}, 
{
  "hours":0
  "file":14
}, 
{
  "hours":0
  "virus":59
}, 
]

I would like to create the desired output without using multiple SQL queries in a foreach loop. Full code below-

$query = "SELECT hour(generated_time) as hours, subtype, count(subtype) as y from description group by subtype, hours order by hours asc, y desc";
$result = mysql_query($query) or die(mysql_error());

$output = array();
$data = array();

while ($row = mysql_fetch_assoc($result)) {
    $data["time"] => $row['hours'];
    $data[$row['subtype']] => $row['y'];
    array_push($output, $data);
}

echo json_encode($output);
  • 写回答

3条回答 默认 最新

  • doumingchen3628 2014-04-04 18:56
    关注

    Just run the SQL query once, and loop over the results and put each row in its correct spot.

    Something like this:

    $output = array();
    
    while ($row = mysql_fetch_assoc($result)) {
        $key = intval($row['hours']);
        if(!isset($output[$key])){
            $output[$key] = array('hours' => $key);
        }
        $output[$key][$row['subtype']] = intval($row['y']);
    }
    
    echo json_encode($output);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源