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条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)