我有一个非常奇怪的问题。我正在查询数据并将其格式化为 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;
最佳答案
请停止您正在做的事情并查看: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);
关于PHP SQL - 由于 ",",按日期排序失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24810102/