dswy34539 2014-05-07 15:06
浏览 37
已采纳

错误的输出json_encode PHP

I am using this code to build an array and encode it to JSON.

   while($row = mysqli_fetch_array($sql)) {

   $results[] = array(
      'wdatatype' => $row['wdatatype'],
      'wdb' => $row['wdb'],
      'wbyte' => $row['wbyte'],
      'wbit' => $row['wbit'],
      'bitval' => $row['bitval'],     
   );

   }
       $json = json_encode($results);
       echo $json;

The output is this

     [{"wdatatype":"DB","wdb":"100","wbyte":"0","wbit":"0","bitval":"1"}] 

But for my jQuery script I need the output to be

     {"wdatatype":"DB","wdb":"100","wbyte":"0","wbit":"0","bitval":"1"}

How do I accomplish this?

Thanks!

  • 写回答

1条回答 默认 最新

  • doupa8922 2014-05-07 15:07
    关注

    You're problem seems to stem from the fact that you're creating a multi-dimensional array. You're pushing an array as an element of the existing $results array. For you're desired output, $results should be an associative array, not an array of associative arrays.

    Provided there is only one row in your result set, try this instead:

    // Remove the while loop if you're only returning a single row
    // such as with a LIMIT = 1 clause in your SQL statement.
    $row = mysqli_fetch_array($sql);
    
    // Push the single row as an array into $result
    $results = array(
        'wdatatype' => $row['wdatatype'],
        'wdb' => $row['wdb'],
        'wbyte' => $row['wbyte'],
        'wbit' => $row['wbit'],
        'bitval' => $row['bitval'],     
     );
    
    // Now echo the json_encode
    echo json_encode($results);
    

    When converted using json_encode, the above will turn into a single object like so:

    {"wdatatype":"DB","wdb":"100","wbyte":"0","wbit":"0","bitval":"1"}
    

    rather than an array of objects.

    Note: As @PankajGarg and @AmalMurali pointed out this should be used if you're only returning a single row. Failing to remove the while loop and returning a result set of more than one row will yield you a return of the last row only.

    For a result set containing multiple rows, your current structure will work perfectly.

    Alternatively as @Nilpo pointed out, you can simplify the above process by using mysqli_fetch_assoc() to return an associative array for you.

    $row = mysqli_fetch_assoc($sql);
    
    // Now echo the json_encode
    echo json_encode($row);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路