我有此代碼,允許用戶輸入一個搜索欄的問題。然後,這段代碼將採取這個問題,並在數據庫中尋找有問題的單詞。然後計算每個問題的匹配詞數。一旦完成,然後顯示前4個最匹配的問題取決於有多少單詞匹配。 然而,目前它顯示從最低的單詞匹配到最高的單詞匹配(從低到高)的這些匹配,我反其道而行,以便它首先顯示最佳匹配(從高到低)。如何在此代碼中執行此操作?
<?php
include("config.php");
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //User enetered data
$search_term = str_replace ("?", "", $search_term); //remove any question marks from string
$array = explode(" ", $search_term); //Seperate user enterd data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array); //Query to select data with word matches
$r = mysql_query($q);
$count = 0; //counter to limit results shown
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title']; //result from query
$thetitle = str_replace ("?", "", $thetitle); //remove any question marks from string
$title_array[] = $thetitle; //creating array for query results
$newarray = explode(" ", $search_term); //Seperate user enterd data again
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value); //Seperate each result from query
$wordmatch = array_diff_key($thenewarray, array_flip($newarray));
$result = array_intersect($newarray, $wordmatch);
$matchingwords = count($result); //Count the number of matching words from user entered data and the database query
}
if(mysql_num_rows($r)==0)//no result found{
echo "<div id='search-status'>No result found!</div>";
}
else //result found
{
echo "<ul>";
$title = $row['title'];
if ($matchingwords >= 4){
?>
<li><a href='<?php echo $row['url']; ?>'><?php echo $title ?><i> No. matching words: <?php echo $matchingwords; ?></i></a></li>
<?php
$count++;
if ($count == 5) {break;
}
}else{
}
}
echo "</ul>";
}
?>
您應該使用純SQL或類似lucene的方法來做到這一點 – Ron 2012-08-04 07:48:36
請不要使用'mysql_ *'函數,它們不再被維護,並且社區已經開始[deprecation process](http://goo.gl/ KJveJ)。相反,您應該瞭解[準備好的語句](http://goo.gl/vn8zQ)並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli的)。如果你不能決定,[本文](http://goo.gl/3gqF9)將有助於選擇。如果你想學習,[這裏是一個很好的PDO相關教程](http://goo.gl/vFWnC)。 – vascowhite 2012-08-04 07:54:41
您確定此代碼有效嗎?對我來說,while()永遠不會關閉。除此之外,我建議你使用比「$ newarray」和「$ thenewarray」更好的變量名稱。另外:你永遠不會將$ title_array聲明爲一個數組。 這就是說,我會扭轉顯示的數組。 – 2012-08-04 07:55:02