[英]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.