6

我想从我的数据库中检索一些标签,它们的形式是:

topic_id       tags
   1        `tag1,tag2,tag3`
   2        `tag1,tag4,tag5`
   3        `tag2,tag4,tag5`
   4        `tag6,tag7,tag2`

我想要这样的东西:

tag1 tag2 tag3 tag4 tag5 tag6 tag7

即所有唯一标签

这样我就可以将每个标签包装在一个链接中,以便对具有此类特定标签的新闻文章进行分组。

到目前为止,我编写的以下查询不起作用:

$tags = mysql_query("SELECT tags, topic_id
                       FROM forum_topics
                       WHERE topic_id > 0")  or die (mysql_error());
                    while($tag = mysql_fetch_assoc($tags)){   
                    $split_tags  = "$tag";
                    $pieces = explode(",", $split_tags);
                    echo $pieces ;

当我这样做的时候 print_r($pieces);

我有Array ( [0] => Array ) Array ( [0] => Array ) Array ( [0] => Array ) Array ( [0] => Array )

这不是我想要的。

因为现在我的表结构看起来像这样topic_id , topic_head, topic_body, topic_tag, topic_date, topic_owner.. 我怎样才能进一步使 topic_tag 正常。

4

3 回答 3

3

如果您规范化您的数据库设计,那么您可以通过以下方式轻松获得所有不同的标签

SELECT DISTINCT tags FROM forum_topics WHERE topic_id > 0

但是现在,使用您的数据库结构,您不能这样做,您必须获取所有标签并 array_unique在它们上使用。

$tags = array();
$rows = mysql_query("SELECT tags FROM forum_topics WHERE topic_id > 0")  or die (mysql_error());
while($row = mysql_fetch_assoc($rows)){   
  $tags = array_merge($tags, explode(',' $row['tags']));
}
$tags = array_unique($tags);
print_r($tags);

但即使你能做到这一点,规范化你的数据库设计也是最好的选择。

于 2012-09-10T02:12:43.510 回答
2

试试这个:

$tags = "";
while($row = mysql_fetch_assoc($tags)) {   
    $tags .= $row["tags"] . ",";
}

$tags = rtrim($tags, ",");
$pieces = explode(",", $tags);

print_r($pieces); // all of them

$pieces = array_unique($pieces);

print_r($pieces); // distinct

...正如Jonah Bishop 已经提到的,请避免mysql_*使用函数。

于 2012-09-10T02:07:10.327 回答
0
select distinct tags from forum_topics;
于 2012-09-10T02:08:24.237 回答