2017-09-10 51 views
0

我有一些代碼,從MySql表中獲取用戶輸入值和列,我需要它運行百分比比較,並返回百分比,最高第一,第二最高,第三位等等.....尋找最近的百分比匹配到2個字符串,並返回下一個最接近

這是我使用至今代碼:

<?php 
 

 
$result_while = mysql_query("SELECT name FROM store_table"); 
 

 
$array = array(); 
 
while ($row = mysql_fetch_array($result_while)) { 
 
    $array[] = $row[name]; 
 
} 
 

 
$words = $array; 
 

 
$string2= "Mr Peter Smith"; 
 

 
foreach ($words as $word) { 
 

 
$percent = (1 - levenshtein($word, $string2)/max(strlen($word),strlen($string2))) * 100; 
 

 
$word . " - Percent match is: " . $percent[$word] . " </br>"; 
 
//60% 
 

 
} 
 

 

 
function compareStrings($s1, $s2) { 
 
    //one is empty, so no result 
 
    if (strlen($s1)==0 || strlen($s2)==0) { 
 
     return 0; 
 
    } 
 

 
    //replace none alphanumeric charactors 
 
    //i left - in case its used to combine words 
 
    $s1clean = preg_replace("/[^A-Za-z0-9-]/", ' ', $s1); 
 
    $s2clean = preg_replace("/[^A-Za-z0-9-]/", ' ', $s2); 
 

 
    //remove double spaces 
 
    while (strpos($s1clean, " ")!==false) { 
 
     $s1clean = str_replace(" ", " ", $s1clean); 
 
    } 
 
    while (strpos($s2clean, " ")!==false) { 
 
     $s2clean = str_replace(" ", " ", $s2clean); 
 
    } 
 

 
    //create arrays 
 
    $ar1 = explode(" ",$s1clean); 
 
    $ar2 = explode(" ",$s2clean); 
 
    $l1 = count($ar1); 
 
    $l2 = count($ar2); 
 

 
    //flip the arrays if needed so ar1 is always largest. 
 
    if ($l2>$l1) { 
 
     $t = $ar2; 
 
     $ar2 = $ar1; 
 
     $ar1 = $t; 
 
    } 
 

 
    //flip array 2, to make the words the keys 
 
    $ar2 = array_flip($ar2); 
 

 

 
    $maxwords = max($l1, $l2); 
 
    $matches = 0; 
 

 
    //find matching words 
 
    foreach($ar1 as $word) { 
 
     if (array_key_exists($word, $ar2)) 
 
      $matches++; 
 
    } 
 

 
    return ($matches/$maxwords) * 100;  
 
} 
 
?>

這工作得很好,給我所有的一長串名字和紅色百分比值旁邊。我需要的是最高的第一,然後按順序.....

我需要輸出範圍選擇下拉框,如果這是有道理的.....但也有能力挑選最高在我的頁面上顯示在一個單獨的行.....

在此先感謝。

達米安

+0

請停止使用PHP的過時mysql_ API – Strawberry

回答

0

試着做這行:

foreach ($words as $word) { 
    $percent = (1 - levenshtein($word, $string2)/max(strlen($word),strlen($string2))) * 100; 
    $word . " - Percent match is: " . $percent[$word] . " </br>"; 
//60% 
} 

此:

foreach ($words as $word) { 
    $percent[$word] = (1 - levenshtein($word, $string2)/max(strlen($word),strlen($string2))) * 100; 
} 

然後給數組排序從最大到最小:

$percent = arsort($percent); 

然後回顯此:

foreach ($percent as $key => $value) { 
    echo $key . " - Percent match is: " . $value . " </br>"; 
} 
+0

「$%的[$單詞] =(1 - 萊文斯坦($字,$字符串2)/ MAX(strlen的($字),strlen的($字符串2)))* 100;」想要發生如果單詞有相同的百分比?數組密鑰將被覆蓋。 –

+0

不知道爲什麼數組鍵會被覆蓋,如果值是相同的。如果密鑰相同,那麼值會被覆蓋。 –

+0

謝謝傑夫馬特森 - 這工作完美,確實根據需要排序 - 感謝您的幫助..... –