简体   繁体   English

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

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

I want to retrieve some tags from my database, they are in the form: 我想从我的数据库中检索一些标签,它们的形式如下:

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

I want to have something like this: 我想要这样的东西:

tag1 tag2 tag3 tag4 tag5 tag6 tag7

ie all unique tags 即所有独特的标签

So that I can wrap each tag in a link in order to group news articles that has such specific tags. 因此,我可以将每个标记包装在一个链接中,以便对具有此类特定标记的新闻文章进行分组。

This following query I've written so far is not working: 我到目前为止写的以下查询无法正常工作:

$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 ;

When I did print_r($pieces); 当我做print_r($pieces);

I got Array ( [0] => Array ) Array ( [0] => Array ) Array ( [0] => Array ) Array ( [0] => Array ) 我得到了Array ( [0] => Array ) Array ( [0] => Array ) Array ( [0] => Array ) Array ( [0] => Array )

Which was not what I was looking for. 这不是我想要的。

As it is now my table structure looks like this topic_id , topic_head, topic_body, topic_tag, topic_date, topic_owner .. How can I further make the topic_tag normal. 因为现在我的表结构看起来像topic_id , topic_head, topic_body, topic_tag, topic_date, topic_owner ..如何进一步使topic_tag正常。

If you normalize your database design, then you could get all the distinct tags very easy by 如果您规范化数据库设计,那么您可以非常轻松地获得所有不同的标签

SELECT DISTINCT tags FROM forum_topics WHERE topic_id > 0

But now, with your database structure, you can't do this, you have to get all the tags and use array_unique on them. 但是现在,使用您的数据库结构,您无法执行此操作,您必须获取所有标记并对其使用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);

But even you could do this, normalize your database design is the best choice. 但即使你可以做到这一点,规范化你的数据库设计是最好的选择。

Try this: 试试这个:

$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

...and as Jonah Bishop already mentioned , please avoid mysql_* functions. ......正如Jonah Bishop已经提到的那样 ,请避免使用mysql_*函数。

select distinct tags from forum_topics;

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

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