连接两个表并通过json响应值

jmo0nnb3  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(283)

我有个问题 JSON 代码。我想附和一下:

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

我使用的代码是:

$stmt = $db->prepare("SELECT fd_posts.post_content , fd_posts.post_title , fd_posts.id, fd_term_relationships.term_taxonomy_id  FROM fd_posts INNER JOIN fd_term_relationships 
ON fd_posts.id=fd_term_relationships.object_id WHERE fd_posts.post_type='hospitals'");

    $stmt->execute();
    $myarr = array();
    while ($data = $stmt->fetch()) {
        $myarr[] = array('id' => $data['id'], 'post_title' => $data['post_title']);

    }
    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"}
]

我怎样才能改变我的生活 PHP 代码以回显所需的 JSON ?

b4lqfgs4

b4lqfgs41#

尝试此代码

$stmt = $db->prepare("SELECT fd_posts.post_content, fd_posts.post_title , fd_posts.id, fd_term_relationships.term_taxonomy_id 
                    FROM fd_posts 
                    INNER JOIN fd_term_relationships ON fd_posts.id = fd_term_relationships.object_id 
                    WHERE fd_posts.post_type='hospitals'");

$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);

相关问题