2011-04-05 76 views
1

我被困在一個問題上,並希望得到一些指導。我正在使用一個編碼非常糟糕的舊系統,並且沒有對用戶輸入進行任何驗證或清理,因此我正在使用的數據庫有點小心。Mysql結果和數組操作

我有一列名爲「標籤」,用於文章標籤的問題。但每一行出現這樣的,以及它們之間的不同:

標籤標籤1標籤2標籤3

OR

標籤1,標籤2,標籤

但我需要將它們結合起來並將它們放入一個數組中,每個數字出現的次數如下所示:

  • 標籤(2)
  • TAG1(2)
  • TAG2(2)
  • 標籤3(1)

因爲我不是最精明與PHP,林不知道我是否正確解決問題?

即時通訊新操作數組在這個規模,這就是爲什麼我卡在這一點。你可以查看下面的例子,我在下面做什麼:

$sql = "SELECT tags, approved FROM articles WHERE approved = '1' "; 
    $result = mysql_query($sql); 

while($rows = mysql_fetch_array($result)) { 
    $arr = $rows['tags']; 
    $arr = str_replace(", ", " ", $arr); // attempting to clean up the data, so that each word appends with a space. 
    $arr = str_replace(" ", " ", $arr); 

    // Don't know what to do next, or if this is even the right way to do it. 

} 

任何幫助表示讚賞。

謝謝,利亞

+0

我想我會被卡住,因爲腳本輸出每行的數組,林不知道如何去操作,和所有我過去一小時的嘗試都失敗了 – Lea 2011-04-05 15:39:39

+0

您可以將字符串轉換爲具有'explode'函數的數組。 – FrustratedWithFormsDesigner 2011-04-05 15:40:56

+0

@FrustratedWithFormsDesigner - 是的,但這並不涉及每行數據格式化的方式。它把它到一個數組,如: 陣列(){ [0] =>標記中,tag1,TAG3,TAG4 [1] =>標記,TAG2,tag6,tag7 } – Lea 2011-04-05 15:45:26

回答

2

也許這會有所幫助。修改您的代碼以便爲每個查詢設置一個$tagArr。如果你需要一個全面的標籤陣列,它會有點不同,但可以很容易地使用下面的代碼進行編碼。

while($rows = mysql_fetch_array($result)) { 
    $arr = $rows['tags']; 
    $arr = str_replace(", ", " ", $arr); // attempting to clean up the data, so that each word appends with a space. 

    // Don't know what to do next, or if this is even the right way to do it. 

    $tagArr = array(); 
    $current_tags = explode(" ", $arr); 
    foreach($current_tags as $tag) { 
    if(!array_key_exists($tag, $tagArr)) { 
     $tagArr[$tag] = 1; 
    } else { 
     $tagArr[$tag] = $tagArr[$tag]++; 
    } 
    } 

    // now $tagArr has the tag name as it's key, and the number of occurrences as it's value 
    foreach($tagArr as $tag => $occurrences) { 
    echo $tag . '(' . $occurrences . ')<br />'; 
    } 
} 
+0

無需爲* str_replace函數空間與空間*線。 – simshaun 2011-04-05 15:56:40

+0

好的謝謝。我如何使用它來輸出列表? – Lea 2011-04-05 16:05:26

+1

@Lea更新了代碼。我剛剛遍歷新的'$ tagArr'數組並回顯信息。還刪除了不需要的'str_replace'。 – 2011-04-05 16:12:23