doutui4649 2014-06-09 08: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 08: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.

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

报告相同问题?

悬赏问题

  • ¥20 关于#alphatensor#的问题,如何解决?(标签-神经网络 强化学习|关键词-复现)
  • ¥15 (有偿)在ANSYS中 .anf文件
  • ¥45 关于#芯片#的问题:组合逻辑电路设计
  • ¥15 基与机器学习和时间序列分析预测养老服务需求趋势
  • ¥100 求连续两帧图像在水平和垂直上偏移
  • ¥15 mysql全文索引查找指定必须关键词word无效
  • ¥15 Verilog hdl密码锁设计
  • ¥35 基于python的有ssl加密传输的socket聊天室
  • ¥15 数码管亮度控制器设计
  • ¥15 kafka客户端跨网段访问,看日志提示连接的还剩内网地址,且访问不通