Reputation: 485
im using the following code to search for similar text. But for some reason it only returns the same value no matter what i search. can someone see what the issue might be?
$result = mysql_query("SELECT keyword FROM search");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['keyword'];
}
foreach ($storeArray as $key){
//echo "'".$key."'";
}
$my_word = $_POST['value'];
$all_words = array(
"'".$key."'"
);
$bestMatch = array('word' => $my_word, 'match' => 2);
foreach($all_words as $word) {
similar_text($word, $my_word, $percent);
if($percent > $bestMatch['match']) $bestMatch = array('word' => $word, 'match' => $percent);
}
if($bestMatch['match'] < 100) echo 'Did you mean: <strong>' . $bestMatch['word'] . '</strong>';
Upvotes: 0
Views: 469
Reputation: 706
I edited it a little, tell me if this is what you want.
$my_word = $_POST['value'];
$bestMatch = array('word' => $my_word, 'match' => 2);
$result = mysql_query("SELECT keyword FROM search");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
//run similar text on each row
similar_text($row['keyword'], $my_word, $percent);
//if row has a better score, overwrite $bestMatch
if ($percent > $bestMatch['match'])
$bestMatch = array('word' => $row['keyword'], 'match' => $percent);
}
if ($bestMatch['match'] < 100)
echo 'Did you mean: <strong>' . $bestMatch['word'] . '</strong>';
EDIT: don't forget that similar_text
was shown to give good results only for words who already have a big similarity (in terms of length mainly), I think it's an 80% resemblance (combining both character counts and lengths). Not 100% sure though...
Upvotes: 1
Reputation: 916
It appears you're doing this in your code, and can explain only getting one result.
$all_words = array(
"'".$key."'"
);
foreach($all_words as $word) {
// ...
}
what you're doing is running a foreach()
on $key
, which doesn't exist, and therefore getting the closest match to ''
.. which will always be the same thing.
Try changing that foreach()
to foreach($storeArray as $word)
, or something similar.
here are some debug tactics - put this code above if($bestMatch['match'] < 100)
.
echo '<pre>';
echo $my_word;
print_r($storeArray);
print_r($all_words);
echo '/<pre>';
what you're looking for is that $all_words
contains all of the words you want to be running similar_text()
on.
Upvotes: 0