方括号外的JSON丢失

时间:2014-06-17 03:22:12

标签: php json

我需要在数组中包含JSON对象,如:

[{"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."}]

但是以下是将JSON作为单独的对象输出:

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

像:

{"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 个答案:

答案 0 :(得分:1)

目前,由于在循环期间调用json结构,因此json结构的构建效果不佳。必须在构建数组(在本例中为$data)之后调用它。考虑这个例子:

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

echo json_encode($data);
相关问题