我正在创建一个允许用户输入问题的搜索功能,然后我的代码将与我的 MySQL 数据库中已有的问题匹配尽可能多的单词,并根据匹配的单词数量显示前 5 个结果这个问题。
我使用count(
) 函数来计算匹配单词的数量,但是目前显示的结果显示为数据库中具有 50% 或更多单词匹配的前 5 个结果。我希望结果首先显示为最高匹配,然后对数据库中的每个结果进行向下处理,但只显示前 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){
?>
<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>";
}
?>
下图显示了当我在搜索栏中搜索“如何制作自己的网站”时发生的情况。我已经在数据库中有几个问题要测试,它们都是相似的问题,最后一个条目与我提出的问题完全匹配,但由于它目前将它们显示为前 5 个数学结果,它忽略了完全匹配。这是该搜索的结果。
我添加了一些代码,显示每个问题中有多少单词匹配,以便您可以看到它工作得更好。巧合的是,它按升序显示数据库中的前 5 个匹配结果。
我需要添加什么代码来安排它,以便它首先显示整个数据库中最接近的匹配,然后是第二个最佳匹配,第三个等等......?