我在var中保存了一个字符串值,我想将它与数组进行比较并打印最接近匹配的数组编号,同时区分大小写。
所以问题是我如何在我的数组中找到最接近的匹配$bio
,在这种情况下,它将 4
我见过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 :(得分: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
答案 1 :(得分:0)
使用max
$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