php foreach中的JSON值给出了不正确的json编码输出

时间:2017-11-28 18:05:54

标签: php json

我有ajax url php代码如下:

<?php
if (isset($_POST["icdmaincode"]) && !empty($_POST["icdmaincode"])) 
{
    $icd_main_code = strip_tags(trim($_POST["icdmaincode"]));
}
$stmt5 = $conn->prepare("SELECT icd_sub_code,icd_sub_code_description 
                        FROM icd_sub_code 
                        WHERE icd_main_code = :icdmaincode");
$stmt5->bindValue(':icdmaincode', $icd_main_code);
$stmt5->execute();
$row = $stmt5->fetchAll(PDO::FETCH_ASSOC);
foreach($row as $key => $value)
{
    echo json_encode(array($key => $value));
}
$conn = null;
?>

并且输出如下无效json

[{"icd_sub_code":"icdcat1-1","icd_sub_code_description":"(A00-A09) Intestinal infectious diseases"}]
{"1":{"icd_sub_code":"icdcat1-2","icd_sub_code_description":"(A15-A19) Tuberculosis"}}
{"2":{"icd_sub_code":"icdcat1-3","icd_sub_code_description":"(A20-A28) Certain zoonotic bacterial diseases"}}

因此以下ajax成功代码无效:

success: function(data){
    var subcode = data.icd_sub_code;
    var subcodedescription = data.icd_sub_code_description;
    subcode = JSON.parse(subcode);  
    alert(subcode); 
    .....

我做错了什么?我怎么解决呢?

1 个答案:

答案 0 :(得分:2)

通常你会构建一个数组,编码然后显示:

foreach($row as $key => $value)
{
    $data[] = array($key => $value);
}
echo json_encode($data);

但实际上你已经在这种类型的数组中拥有它,所以不需要循环:

echo json_encode($row);

另外,仅供参考empty只检查isset

if (!empty($_POST["icdmaincode"]))