2009-11-25 55 views
0

我有一個標籤數組,我從數據庫中提取,我將標籤導出到標籤雲中。我被困在獲得這個詞的第一個例子。例如:php只從數組中獲得單詞的第一次出現

$string = "test,test,tag,tag2,tag3"; 

$getTags = explode("," , $string); 
    foreach ($getTags as $tag){ 
    echo($tag); 
    } 

這會輸出測試標籤兩次。起初,我以爲我可以使用stristr做這樣的事情:

foreach ($getTags as $tag){ 
     $tag= stristr($tag , $tag); 
     echo($tag); 
    } 

這顯然是愚蠢的邏輯並不起作用,stristr似乎只替換第一次出現這樣類似「測試123」只會擺脫的「測試」,並會返回「123」我見過這也可以用正則表達式完成,但我還沒有找到一個動態的例子。

感謝,
布魯克

編輯:unique_array()作品,如果我用一個靜態的字符串,但不會與數據從數據庫中工作,因爲我使用一個while循環來獲取每個行數據。

$getTag_data = mysql_query("SELECT tags FROM `news_data`"); 
if ($getTag_data) 
{ 

    while ($rowTags = mysql_fetch_assoc($getTag_data)) 
    { 
    $getTags = array_unique(explode("," , $rowTags['tags'])); 
     foreach ($getTags as $tag){ 
     echo ($tag); 
     } 
    } 
} 

回答

1

我假設在你的表中的每一行包含一個以上的標籤,昏迷隔開,像這樣:

Row0: php, regex, stackoverflow 
Row1: php, variables, scope 
Row2: c#, regex 

如果是這樣的話,試試這個:

$getTag_data = mysql_query("SELECT tags FROM `news_data`"); 

//fetch all the tags you found and place it into an array (with duplicated entries) 
$getTags = array(); 
if ($getTag_data) { 
    while ($row = mysql_fetch_assoc($getTag_data)) { 
    array_merge($getTags, explode("," , $row['tags']); 
    } 
} 

//clean up duplicity 
$getTags = array_unique($getTags); 

//display 
foreach ($getTags as $tag) { 
    echo ($tag); 
} 

我'd指出這不是有效的。

另一種選擇(這裏已經提到過)將使用標籤作爲數組鍵,其優點是能夠輕鬆地對它們進行計數。
你可以做這樣的:

$getTag_data = mysql_query("SELECT tags FROM `news_data`"); 

$getTags = array(); 
if ($getTag_data) { 
    while ($row = mysql_fetch_assoc($getTag_data)) { 
    $tags = explode("," , $row['tags']); 
    foreach($tags as $t) { 
     $getTags[$t] = isset($getTags[$t]) ? $getTags[$t]+1 : 1; 
    } 
    } 
} 

//display 
foreach ($getTags as $tag => $count) { 
    echo "$tag ($count times)"; 
} 
  • 請記住這都不代碼進行了測試,它只是使你的想法。
+0

謝謝你的工作,我不得不在'foreach'循環中添加'$ t = trim($ t);'將key設置爲「test」與「test」不同。謝謝您的幫助! – BandonRandon 2009-11-26 00:27:49

4

使用array_unique()

$string = "test,test,tag,tag2,tag3"; 

$getTags = array_unique(explode("," , $string)); 
foreach ($getTags as $tag){ 
    echo($tag); 
} 
+0

這看起來應該從閱讀PHP手冊開始工作。它適用於如果我使用靜態字符串,但如果我從MySQL數據庫中提取數據的話。我認爲這可能是因爲我從多行中拉出來並爆炸每一行。 – BandonRandon 2009-11-25 22:19:46

2

用你的話作爲鑰匙到字典中,沒有價值。

$allWords=array() 
foreach(explode("," , $string) as $word) 
    $allWords[$word]=true; 
//now you can extract these keys to a regular array if you want to 
$allWords=array_keys($allWords); 

當你在它的時候,你也可以數它們!

$wordCounters=array() 
foreach(explode("," , $string) as $word) 
{ 
    if (array_key_exists($word,$wordCounters)) 
    $wordCounters[$word]++; 
    else 
    $wordCounters=1; 
} 

//word list: 
$wordList=array_keys($wordCounters); 

//counter for some word: 
echo $wordCounters['test']; 
+0

這是IMO的勝利者。應該也是最快的。 – 2009-11-26 00:59:00

相關問題