1

我有两张桌子——食物和标签。食物中的每一行都有相应的标签。我想用这些标签输出每一行,即:

餐桌食物:

编号 | 姓名

1 | 面包

2 | 肉

表标签:

参考ID | 标签

1 | 面包店

1 | 小麦

2 | 奶牛

所需的输出是:

{“结果”:[{“id”:“1”,“名称”:“面包”,“标签”:[“面包店”,“小麦”]},

{"id":"2","name":"meat","tags":["cow"]}] }

到目前为止,我有这个:

$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) . '}';

我正在考虑循环浏览每一种食物,然后标记并找到匹配的配对,但对我来说似乎很重(考虑到我可以有数千行的事实)。你有什么建议吗?

4

1 回答 1

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) . '}';
}   
于 2013-07-02T14:17:20.127 回答