面临从两个SQL结果构造复杂JSON对象的问题

时间:2015-04-07 00:17:57

标签: php mysql json

当第二个SQL查询没有返回任何内容时,我很难从两个SQL结果中构造这种JSON对象。

{"options":["American Black Bear", "Asiatic Black Bear", "Brown Bear", "Giant Panda", "Sloth Bear", "Sun Bear", "Polar Bear", "Spectacled Bear"], "selected":[]}

我希望始终拥有选中的键和空数组,即使SQL语句中没有返回任何行。

这是运行中执行两个查询的PHP代码

    $sql = "SELECT categorie FROM cc_categorie order by categorie";

    $sth= $dbh->query($sql);
    while($row = $sth->fetch(PDO::FETCH_ASSOC)){     
        $rows['options'][] = $row['categorie'];
    }
    $sql = "SELECT cc_categorie.categorie 
    FROM cc_coupon_by_categorie, cc_categorie 
    WHERE cc_categorie.id_categorie = cc_coupon_by_categorie.id_categorie
    and cc_coupon_by_categorie.id_coupon = 10"; //no lines are returned (I know I need to use join on...)

    $sth= $dbh->query($sql);
    while($row = $sth->fetch(PDO::FETCH_ASSOC)){     
        $rows['selected'][] = $row['categorie'];
    }

    print json_encode($rows);

0 个答案:

没有答案