dourou9477 2017-04-27 11:25
浏览 93
已采纳

找到最接近的匹配字符串到数组PHP

I have a string value held in a var, I want to compare it against a array and print the array number that is the nearest match whilst being case sensitive.

so the question is how do I find the nearest match within my array to my var $bio in this case it would be 4

I have seen pregmatch but am unsure on how to use it in this case.

Code I have

<?php
$bio= "Tom, male, spain";

$list= array(
    1 => array("Tom", "male", "UK"),
    8 => array("bob", "Male", "spain"),
    4 => array("Tom", "male", "spain"),
    9 => array("sam", "femail", "United States")
);

function best_match($bio, $list)

{

}

I was thinking something like thinking

$matches  = preg_grep ($bio, $list);

print_r ($matches);
  • 写回答

2条回答 默认 最新

  • dtw52353 2017-04-27 11:53
    关注

    Another way using array_intersect:

    $bio= "Tom, male, spain";
    
    $list= array(
        1 => array("Tom", "male", "UK"),
        8 => array("bob", "Male", "spain"),
        4 => array("Tom", "male", "spain"),
        9 => array("sam", "femail", "United States")
    );
    
    function best_match($bio, $list) {
        $arrbio = explode(', ', $bio);
        $max = 0;
        $ind = 0;
        foreach($list as $k => $v) {
            $inter = array_intersect($arrbio, $v);
            if (count($inter) > $max) {
                $max = count($inter);
                $ind = $k;
            }
        }
        return [$ind, $max];
    }
    list($index, $score) = best_match($bio, $list);
    echo "Best match is at index: $index with score: $score
    ";
    

    Output:

    Best match is at index: 4 with score: 3
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?