我有两张桌子 - 食物和标签。来自食物的每一行都有相应的标签。 我想用这些标签输出每一行,即:
1 |面包
2 |肉
1 |面包店
1 |小麦
2 |牛
{ “结果”: [{ “ID”: “1”, “名称”: “面包”, “标签”:[ “面包店”, “小麦”]},
{ “ID”: “2”, “名称”: “肉”, “标签”:[ “牛”]}] }
到目前为止,我有这个:
$db = getConnection();
$stmt = $db->query($sql);//get every column from every food
$food = $stmt->fetchAll(PDO::FETCH_OBJ);
$tagsSql="select id_reference,tag FROM tags T,food F WHERE F.id=T.food_id_reference";
$stmt = $db->query($tagsSql);
$tags=$stmt->fetchAll(PDO::FETCH_OBJ);
echo '{"results":' . json_encode($food) . '}';
我正在考虑骑自行车穿过每一种食物并且永远标记并找到匹配的对,但它对我来说似乎非常重要(考虑到事实,我可能有数千行)。你有什么建议吗?
答案 0 :(得分:0)
未经测试,但我认为这样的事情对您有用
$db = getConnection();
$stmt = $db->query($sql);//get every column from every food
$tagsSql="select F.id as id, F.name as name, group_concat(T.tag SEPARATOR ',') as tags FROM tags T,feeds F WHERE F.id=T.feed_id_reference group by feed_id_reference";
$stmt = $db->query($tagsSql);
for($x = 0; $x < count($tags); $x++){
$tags[$x]->{"tags"} = explode(",", $tags[$x]->{"tags"});
echo '{"results":' . json_encode($tags) . '}';
}