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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置