繁体   English   中英

如何从逗号分隔的标签中选择唯一关键字

[英]how to select unique keywords from a comma separated tags

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

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM