2017-09-10 104 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

谢谢杰夫马特森 - 这工作完美,确实根据需要排序 - 感谢您的帮助..... –