重複の可能性:
このコードの結果を並べ替えるには?
ユーザーが質問を検索できるようにする検索機能を作成すると、質問内の一致する単語の数を数えることで、上位 5 つの最も一致する結果が表示されます。基本的に、一致する単語の数が最も多い質問である最良の一致を最初に表示する順序が必要です。
これが私が持っているコードです。
<?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
$search_count = str_word_count($search_term); //count words of string entered by user
$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'];
$percentage = '.5'; //percentage to take of search word count
$percent = $search_count - ($search_count * $percentage); //take percentage off word count
if ($matchingwords >= $percent){
$finalarray = array($title => $matchingwords);
foreach( $finalarray as $thetitle=>$countmatch ){
?>
<li><a href="#"><?php echo $thetitle ?><i> <br />No. of matching words: <?php echo $countmatch; ?></i></a></li>
<?php
}
$count++;
if ($count == 5) {break;
}
}else{
}
}
echo "</ul>";
}
?>
何かを検索すると、次のように表示されます。
各質問の下に一致する単語の数を入力しますが、順序が正しくありません。データベースから 50% の単語が一致する最初の 5 つの質問だけが表示されます。一致する単語の数が最も多い上位 5 つを表示したいと考えています。
これを行うには、どのコードを追加する必要があり、どこに配置しますか?
ありがとう