dscw1223 2014-06-17 03:22 采纳率: 50%
浏览 106
已采纳

方括号外的JSON丢失

I need to have JSON objects inside an array like:

[{"term":"hemisected","description":"Cut into two equal parts; to bisect, especially along a medial longitudinal plane."},{"term":"polyuria","description":"A condition usually defined as excessive or abnormally large production or passage of urine."},{"term":"dyspnoea","description":"Shortness of breath."}]

However the following is outputting JSON as separate objects:

while ($row = mysql_fetch_array($result)) { 
        $data = array(
        'term' => $row['term'],
        'description' => $row['definition']
        );
echo json_encode($data);
}

Like:

{"term":"hemisected","description":"Cut into two equal parts; to bisect, especially along a medial longitudinal plane."}{"term":"polyuria","description":"A condition usually defined as excessive or abnormally large production or passage of urine."}{"term":"dyspnoea","description":"Shortness of breath."} 
  • 写回答

1条回答 默认 最新

  • douwo1862 2014-06-17 03:30
    关注

    Currently, the json structure is not well build because of the fact that it is called during the loop. It must be called after the array (in this case $data) has been built. Consider this example:

    $data = array();
    while ($row = mysql_fetch_array($result)) { 
        $data[] = array(
            'term' => $row['term'],
            'description' => $row['definition'],
        );
    }
    
    echo json_encode($data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大