2012-12-05 62 views
0

我有一句話,我想分成詞,然後在停用詞表中的數據進行檢查。我想統計相同數據的數量(總數)。但總計不會給我相同數據的總數。如何總結我需要的數據?感謝計算與數據字的相同數據表中的

$word ='temporal. the text mining in a evolutionary a theme patterns theme threads clustering'; 
$symbol = array(".", ",", "\\", "-", "\"", "(", ")", "<", ">", "?", ";", ":", "+", "%", "\r", "\t", "\0", "\x0B"); 
$cleanMeta = str_replace($symbol, " ", $word); 
$key  = strtolower($cleanMeta); 
$key = explode(" ", trim($key)); 

foreach($key as $word_key){ 
    $query = mysql_query ("SELECT COUNT(stoplist_word) AS total FROM tb_stopword WHERE stoplist_word = '$word_key'"); 
    while ($row = mysql_fetch_array($query)) { 
     $row1 = $row['total']; 
     echo $row1; 
    } 
} 
+0

你的得到,如果'的var_dump($鍵)foreach'過嗎? – GBD

+0

@GBD'array(14){[0] => string(8)「temporal」[1] => string(0)「」[2] => string(4)「text」[3] => string (6)「mining」[4] => string(2)「in」[5] => string(12)「evolutionary」[6] => string(1)「a」[7] => string(5) )「theme」[8] => string(8)「patterns」[9] => string(0)「」[10] => string(5)「theme」[11] => string(7) 「[12] => string(0)」「[13] => string(10)」clustering「}' –

+0

對於每個關鍵字,你沒有得到'total' – GBD

回答

1

考慮你已經清理輸入字符串,你不需要一個foreach與每一個字一個新的查詢。你可以這樣做:

$word ='temporal. the text mining in a evolutionary a theme patterns theme threads clustering'; 
$symbol = array(".", ",", "\\", "-", "\"", "(", ")", "<", ">", "?", ";", ":", "+", "%", "\r", "\t", "\0", "\x0B"); 
$cleanMeta = str_replace($symbol, " ", $word); 
$key  = trim(strtolower($cleanMeta)); 
$key  = str_replace("'","''",$key); 
$keys  = "'".str_replace(" ","', '", $key)."'"; 

$query = mysql_query ("SELECT COUNT(stoplist_word) AS total FROM tb_stopword WHERE stoplist_word IN ($keys)"); 
$row = mysql_fetch_array($query); 
$total = $row['total']; 

echo $total; 

如果你真的想在foreach使用:

$total = 0; 
foreach($key as $word_key){ 
    $query = mysql_query ("SELECT COUNT(stoplist_word) AS total FROM tb_stopword WHERE stoplist_word = '$word_key'"); 
    while ($row = mysql_fetch_array($query)) { 
     $total += $row['total']; 
    } 
} 
echo $total; 
+0

您可能需要使用'mysqli'或'PDO'和事先準備好的聲明的所有單詞,變量綁定,以避免解析相同SQL一遍又一遍地在'foreach'解決方案中。 – Passerby

+0

我只是用他自己的代碼讓他理解他的使用。更改爲mysqli,儘管強烈建議,但很可能意味着他必須更新他的所有頁面。 –