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

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

报告相同问题?