PHP SQL - 由于","导致按日期排序失败

Dan*_*ers 0 php mysql sql json while-loop

我有一个非常奇怪的问题.我正在查询数据并将其格式化为json.格式工作得很好,但是当我尝试添加一个案例来防止,出现在json的最后一项时,我的SQL语句的"按日期排序"不起作用,我只是通过ID命令它.有什么想法?

$sql = "SELECT * FROM events ORDER BY date";
$res = mysql_query($sql,$con);
$number = mysql_num_rows($res);
$json = 'var event_data={';
$i = 1;
while ($row = mysql_fetch_assoc($res))
    {
    $json .= '"'.$row['id'].'": {';
    $json .= '"loc_id":"'.$row['loc_id'].'"';
    $json .= ', "type":"'.$row['type'].'"';
    $json .= ', "time":"'.$row['time'].'"';
    $json .= ', "date":"'.$row['date'].'"}';
    if ($i < $number)
       {
           $json .= ',';  //<----- this is the problem child
       }else{
           $json .= '';
       }
     $i ++;
    }
$json .= '};';  
echo $json;
Run Code Online (Sandbox Code Playgroud)

sma*_*sey 7

请停止现在正在做的事情并查看:http://php.net/manual/en/function.json-encode.php

构建自己的json编码器很难正确完成,如果你是用PHP做的话,需要花费很多时间.使用PHP构建数据结构,然后在一遍中编码整个事物:

$o = array();
while ( $row = mysql_fetch_assoc($res) ) {
    $n = array();
    $n['loc_id'] = $row['loc_id'];
    $n['type'] = $row['type'];
    # ...
    $o[ $row['id'] ] = $n;
}
echo json_encode($o);
Run Code Online (Sandbox Code Playgroud)