doutui4649 2014-06-09 00:24
浏览 27
已采纳

从MySQL数据库解析JSON的问题

PHP json_encode() at following code:

$con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$query = "SELECT * FROM data limit 1" ;
$results = $con->query($query);
$return = array();
if($results) {
  while($row = $results->fetch_assoc()) {
     $return[] = $row;
  }
}
echo json_encode($return);
$con->close();

creates a JSON object like this:

[{"id":"1","name":"tabo","age":"26","phone":"44444422","comments":""}]

can you please let me know how I can get rid of the [] at begiining and end of the JSON and have only

{"id":"1","name":"tabo","age":"26","phone":"44444422","comments":""}

at output? The reason that I need to do this is accessing the JSON object by using the jQuery.parseJSON() which those [] make the properties undefined!

Thanks

  • 写回答

1条回答 默认 最新

  • dongxunhua2054 2014-06-09 00:27
    关注

    You are putting an array into a variable and turning it into an array. The JSON encode is saying that the object is an array with the [].

    You can get past this by doing the encode right on the spot:

    if($results) {
      while($row = $results->fetch_assoc()) {
         $json=json_encode($row);
      }
    }
    $con->close();
    
    echo $json;
    

    The encoded JSON you are echoing is basically telling you that the object you encoded is an array with all the bits inside it. What you are trying to do is to show the $row as a JSON, not the row inside an array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部