-6ren">
gpt4 book ai didi

php - 如何按照匹配的关键字数量的顺序显示结果?

转载 作者:可可西里 更新时间:2023-11-01 07:57:03 26 4
gpt4 key购买 nike

感谢 youtube 上的精彩视频,您可以访问 here如果您愿意,我可以创建一个 php 搜索引擎。下面是代码:

<?php


//connected to DB

foreach (array('questioncontent') as $varname) {
$questioncontent = (isset($_GET[$varname])) ? $_GET[$varname] : '';
}

?>

<form action="previousquestions.php" method="get">
<p>Search: <input type="text" name="questioncontent" value="<?php echo $questioncontent; ?>" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>

<?php

if (isset($_GET['searchQuestion'])) {

$searchquestion = $questioncontent;
$terms = explode(" ", $searchquestion);

$questionquery = "SELECT * FROM Question WHERE ";

foreach ($terms as $each){
$i++;

if ($i == 1){
$questionquery .= "QuestionContent LIKE '%$each%' ";
} else{
$questionquery .= "OR QuestionContent LIKE '%$each%' ";

}

}

$questionnum = mysql_num_rows($questionresult = mysql_query($questionquery));

else if($questionnum !=0){

$output = "";
$output .= "
<table border='1'>
<tr>
<th>Question</th>
</tr>
";
while ($questionrow = mysql_fetch_array($questionresult)) {
$output .= "
<tr>
<td>{$questionrow['QuestionContent']}</td>
</tr>";
}
$output .= " </table>";

echo $output;

}

}

mysql_close();

?>

现在我有一个问题,如果可能的话如何对搜索结果进行排序。假设在数据库中我有这 3 个语句:

My name
My name is Mayur Patel
My name is Patel

现在假设我在搜索框中输入“name Mayur Patel”,我希望对结果进行排序,以便它首先显示包含所有这些关键字的任何行,然后在显示所有这些行之后显示包含部分关键字的那些行(一个一个地敲掉一个关键字),以便搜索结果将按以下顺序显示:

My name is Mayur Patel (all keywords match in this phrase)
My name is Patel (2 keywords match this phrase which are 'name' and 'Patel')
My name (1 keyword match this phrase which is 'name')

我想知道是否可以根据数据库中短语中匹配的关键字数量对搜索结果进行排序?

最佳答案

当前,您的查询内置代码在完成后看起来像这样:

SELECT * FROM Question WHERE
QuestionContent LIKE '%name%'
OR QuestionContent LIKE '%Mayur%'
OR QuestionContent LIKE '%Patel%'

要获得您要查找的结果,您可以添加如下排序子句,该子句将以类似的方式从关键字列表中生成:

ORDER BY
IF(QuestionContent LIKE '%name%',1,0)+
IF(QuestionContent LIKE '%Mayur%',1,0)+
IF(QuestionContent LIKE '%Patel%',1,0) DESC

基本上它会计算有多少关键字匹配,如果匹配则为关键字计数贡献 1,否则为 0。所以最后,这将产生 3、2、1 作为计数,然后排序使用 DESC 降序排列,因此具有最多匹配关键字的条目首先出现。

演示:http://www.sqlfiddle.com/#!2/eaabc/2


编辑:正如所 promise 的,这里有一种在 PHP 代码中实现的方法:

$questionquery = "SELECT * FROM Question WHERE ";
foreach ($terms as $each) {
$i++;

if ($i == 1){
$questionquery .= "QuestionContent LIKE '%$each%' ";
} else {
$questionquery .= "OR QuestionContent LIKE '%$each%' ";
}
}

$questionquery .= " ORDER BY ";
$i = 0;
foreach ($terms as $each) {
$i++;

if ($i != 1)
$questionquery .= "+";
$questionquery .= "IF(QuestionContent LIKE '%$each%',1,0)";
}
$questionquery .= " DESC";

关于php - 如何按照匹配的关键字数量的顺序显示结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10744588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com