在php中包含一个用于json编码的循环

时间:2018-08-29 05:33:08

标签: php json while-loop encode

我的JSON代码有问题。我想回应一下:

[{"post_title":"hospital-name","term_taxonomy_id":"15,16,20"}, 
{"post_title":"hospital-name","term_taxonomy_id":"15,16,20"} ]  

我对此进行了编码:

$stmt->execute();
$myarr = array();
while ($data = $stmt->fetch()) {
    $myarr[] = array(
        'post_title' => $data['post_title'],
        'term_taxonomy_id' => $data['term_taxonomy_id'], 
    );
}
echo json_encode($myarr, JSON_UNESCAPED_UNICODE);

但最后显示:

[
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"120","post_title":"hospital-name"},
    {"id":"125","post_title":"hospital-name-2"},
    {"id":"125","post_title":"hospital-name-2"},
    {"id":"125","post_title":"hospital-name-2"},
    {"id":"125","post_title":"hospital-name-2"},
    {"id":"125","post_title":"hospital-name-2"},
    {"id":"125","post_title":"hospital-name-2"},
    {"id":"125","post_title":"hospital-name-2"}
]

请帮助我解决这个问题。 实际上,我的循环有问题。

1 个答案:

答案 0 :(得分:0)

我希望您希望将一所医院的所有term_taxonomy_id以逗号分隔成一串。

执行以下操作:-

$myarr = array();   
while ($data = $stmt->fetch_assoc()) {
    $myarr[$data['post_title']] = array(
        'post_title' => $data['post_title'],
        'term_taxonomy_id' => isset($myarr[$data['post_title']]['term_taxonomy_id']) ? $myarr[$data['post_title']]['term_taxonomy_id'].','.$data['term_taxonomy_id'] : $data['term_taxonomy_id']
    );
}
echo json_encode(array_values($myarr), JSON_UNESCAPED_UNICODE);

一个硬编码的示例:-https://eval.in/1051696

参考:-array_values()