我使用下面的代码来搜索相似的文本。但是由于某种原因,无论我搜索什么,它只返回相同的值。有没有人能看看问题出在哪里?
$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>';发布于 2012-07-04 09:08:23
我稍微修改了一下,告诉我这是不是你想要的。
$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>';编辑:不要忘记,similar_text只对那些已经有很大相似性的单词(主要是在长度方面)给出了很好的结果,我认为它有80%的相似性(结合了字符数和长度)。但不是100%确定...
发布于 2012-07-04 09:10:09
看起来你是在你的代码中这样做的,并且只能解释得到一个结果。
$all_words = array(
"'".$key."'"
);
foreach($all_words as $word) {
// ...
}您正在做的是在$key上运行一个不存在的foreach(),从而获得与''最接近的匹配。永远都是一样的东西。
尝试将该foreach()更改为foreach($storeArray as $word)或类似的内容。
以下是一些调试策略-将此代码放在if($bestMatch['match'] < 100)之上。
echo '<pre>';
echo $my_word;
print_r($storeArray);
print_r($all_words);
echo '/<pre>';你要找的是$all_words包含了你想要运行similar_text()的所有单词。
https://stackoverflow.com/questions/11321170
复制相似问题