匹配最近的关联数组值

时间:2014-09-30 12:42:50

标签: php arrays

$searchable=array("Thailand,Chumphon" => "1",
"Thailand,Kalasin" => "2",
"Thailand,Kamphaeng Phet" => "3",
"Thailand,Kanchanaburi" => "4",
"Thailand,Khon Kaen" => "5",
"Thailand,Krabi" => "6",
"Thailand,Krung Thep Mahanakhon (Bangkok)" => "7",
"Thailand,Lampang" => "8",
"Thailand,Lamphun" => "9");

$searchvalue = "Thailand,Bangkok";

希望返回的值为7。

e.g。

function returnvalue($searchvalue,$searchable){

    }

$returnedvalue = returnvalue($searchvalue,$searchable);

echo $returnedvalue; // 7

如何匹配$ searchable的最近/最近值$ searchvalue? 我发现了这个PHP - Nearest value from an array,但仅限于数字。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

您可以在php中使用函数similar_textlevenshtein

- 编辑

例如:

$textDistance = function($a, $b) {
    return levenshtein($a, $b);
};

function getClosest($search, $arr) {
   $closest = null;
   $closestVal = null;
   foreach($arr as $label => $item) {
      if($closest == null || $textDistance($search,$closest) > $textDistance($search,$label)) {
         $closest = $label;
         $closestVal = $item;
      }
   }
   return $closestVal;
}

答案 1 :(得分:0)

下面怎么样?有人想做得更好吗?

$searchable=array("Thailand,Chumphon" => "1",
"Thailand,Kalasin" => "2",
"Thailand,Kamphaeng Phet" => "3",
"Thailand,Kanchanaburi" => "4",
"Thailand,Khon Kaen" => "5",
"Thailand,Krabi" => "6",
"Thailand,Krung Thep Mahanakhon (Bangkok)" => "7",
"Thailand,Lampang" => "8",
"Thailand,Lamphun" => "9");

$searchvalue = "Thailand,Bangkok";

$returnedvalue = searchclosest($searchvalue,$searchable);

echo $returnedvalue; //but the returned value is actually Thailand,Lamphun... it's bad.


function searchclosest($input,$arrayinput){
        $shortest = -1;
        $words=array();

        foreach($arrayinput as $key => $value){
                array_push($words,$key);
        }

        foreach ($words as $word) {

                $lev = levenshtein($input, $word);

                if ($lev == 0) {

                        $closest = $word;
                        $shortest = 0;

                        break;
                }

                if ($lev <= $shortest || $shortest < 0) {
                        $closest  = $word;
                        $shortest = $lev;
                }
        }

        return $closest;
}