2017-04-27 124 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

相關問題