2017-04-27 136 views
0

我有一个字符串值保存在一个变种,我想比较它与阵列和打印数组编号是最接近的匹配,而区分大小写。找到最接近的匹配字符串数组php

所以,问题是我怎么找到我的阵列我VAR $bio在这种情况下,距离最近的比赛将是

我见过pregmatch但我对如何在这种情况下使用它不确定。

代码,我

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

{ 

} 

我想是这样想

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

print_r ($matches); 
+0

*最近的依据是什么比赛*? –

+0

好点不适更新问题 – Beep

回答

0

使用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\n"; 

输出的另一种方式:

Best match is at index: 4 with score: 3 
+0

完美,谢谢 – Beep

1

这可能是一个工作,similar text,即:

$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") 
); 

$percent_old = 0; 
foreach ($list as $key => $value) # loop the arrays 
{ 
    $text = implode(", ", $value); # implode the array to get a string similar to $bio 
    similar_text($bio, $text, $percent); # get a percentage of similar text 

    if ($percent > $percent_old) # check if the current value of $percent is > to the old one 
    { 
     $percent_old = $percent; # assign $percent to $percent_old 
     $final_result = $key; # assign $key to $final_result 
    } 
} 

print $final_result; 
# 4 

PHP Demo

+1

这看起来很有前途,谢谢生病试试,很快接受答案 – Beep