我想从数据库中检索一些标签,它们的形式是:
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正常。
如果您规范化数据库设计,那么可以非常容易地获得所有不同的标签
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);
但即使你可以做到这一点,规范化数据库设计也是最好的选择
试试这个:
$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_*
函数。
select distinct tags from forum_topics;