PHP查找SQL数据库中最匹配的句子


php find sentence with most match in sql database

我正在制作一个问答应用程序,作为它的一部分,它需要看看你以前的问题存储在SQL数据库中,并找到以前的问题,有最匹配的词,然后它会从DB为那行取一个属性。

我已经能够让它为数据库中的每一行生成匹配单词的数组。但我需要一种组织这些数组的方法来选择匹配次数最多的数组。这里是SQL和PHP我已经习惯了。

$questions1 = $_GET['question'];
$questionsarray =  explode(" ",$questions1);

新问题被转换成一个数组,下面它将与match的

中的所有其他问题进行比较。
$sql = "SELECT * FROM records WHERE userid= '24.9.71.79'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
 $questionsasked = $row['old_questions']; 
 // turns old question into an array
 $last_q_array =  explode(" ",$questionsasked);
 //finds matches between the old and new question    
 $intersectarray = array_intersect($last_q_array,$questionsarray);

然后使用array_diff()清除常见单词,以帮助它专注于查找真正的主题

 $cleanedarray = array_diff($intersectarray ,$commonwords);
 //prints the array if it find matches and sets the var
 if(count($cleanedarray)>0) {
    print_r($cleanedarray);
    $desiredattri = $row[last_answer_type];
    echo "<br />----------------<br />";
 }
}
}

我使用print_r只是为了测试。因此,它可以很好地生成一些只显示匹配单词的数组。它看起来像这样

Array ( [3] => card ) 
----------------
Array ( [3] => card [7] => work?  ) 
----------------
Array ( [0] => find [2] => card [7] => work? ) 

现在我需要找到一种方法来解析这些数组并找到匹配最多的数组。我可以使用count()来计算每个数组中的匹配,但仍然需要将该数字与数组的其余计数进行比较,然后使用具有大多数匹配的数组的属性。

您可以尝试这样做。它将使用单词本身作为数组键,数组值是计数。

$result = array();
foreach ($cleanedarray as $word) {
    if (!array_key_exists($word, $result)) {
        $result[$word] = 0;
    }
    $result[$word]++; // keep count using the word as key
}

我相信可能有其他内置的PHP函数可以为您做这些,但这是一种快速的方法,我想到了