简体   繁体   中英

php find sentence with most match in sql database

I am making a question answering app and as a part of it, it needs to look at your previous questions which are stored in a SQL database and find the previous questions that has the most matching words and then it will take an attribute from the DB for that line.

I have been able to get it to produce an array of matching words for each row in the database. But I need a way of organizing those arrays to select the one with the most matches. here is the SQL and the PHP I have used to far.

$questions1 = $_GET['question'];

$questionsarray =  explode(" ",$questions1);

The new question was turned into an array, below it will be compared against all other questions for match's

$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);

It then uses array_diff() to clean out common words to help it focus on finding the true topic

 $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 />";
 }

}
}

I'm using print_r just for testing. So it does a great job of producing a handful of arrays that show just the matching words. that looks something like this

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

So now I need to find a way to parse those arrays and find the one that has the most matches. I can use count() to count the matches in each array but still need to compare that number against the rest of the array counts and then use the attribute of the array with most matches.

You could try something like this. It will use the words themselves as array keys and the array value is the 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
}

I'm sure there might be other built-in PHP functions which could do this for you, but this was a quick-n-dirty way that came to me off hand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM