gpt4 book ai didi

php - 查找与 2 个字符串最接近的百分比匹配,并返回下一个最接近的百分比

转载 作者:行者123 更新时间:2023-11-29 18:26:34 25 4
gpt4 key购买 nike

我有一些代码,它需要用户输入的值和 MySql 表中的一列,我需要它来运行百分比比较并返回百分比,第一最高,第二高,第三高等等......

这是我到目前为止使用的代码:

<?php

$result_while = mysql_query("SELECT name FROM store_table");

$array = array();
while ($row = mysql_fetch_array($result_while)) {
$array[] = $row[name];
}

$words = $array;

$string2= "Mr Peter Smith";

foreach ($words as $word) {

$percent = (1 - levenshtein($word, $string2)/max( strlen($word),strlen($string2) ) ) * 100;

$word . " - Percent match is: " . $percent[$word] . " </br>";
//60%

}


function compareStrings($s1, $s2) {
//one is empty, so no result
if (strlen($s1)==0 || strlen($s2)==0) {
return 0;
}

//replace none alphanumeric charactors
//i left - in case its used to combine words
$s1clean = preg_replace("/[^A-Za-z0-9-]/", ' ', $s1);
$s2clean = preg_replace("/[^A-Za-z0-9-]/", ' ', $s2);

//remove double spaces
while (strpos($s1clean, " ")!==false) {
$s1clean = str_replace(" ", " ", $s1clean);
}
while (strpos($s2clean, " ")!==false) {
$s2clean = str_replace(" ", " ", $s2clean);
}

//create arrays
$ar1 = explode(" ",$s1clean);
$ar2 = explode(" ",$s2clean);
$l1 = count($ar1);
$l2 = count($ar2);

//flip the arrays if needed so ar1 is always largest.
if ($l2>$l1) {
$t = $ar2;
$ar2 = $ar1;
$ar1 = $t;
}

//flip array 2, to make the words the keys
$ar2 = array_flip($ar2);


$maxwords = max($l1, $l2);
$matches = 0;

//find matching words
foreach($ar1 as $word) {
if (array_key_exists($word, $ar2))
$matches++;
}

return ($matches / $maxwords) * 100;
}
?>

这工作正常,并为我提供了所有名称及其旁边的百分比值的长列表。我需要的是先最高的,然后按顺序......

如果有意义的话,我需要将范围输出到选择下拉框......但也能够选择最高的值以显示在页面上的单独行中......

提前致谢。

达米安

最佳答案

尝试制作这一行:

foreach ($words as $word) {
$percent = (1 - levenshtein($word, $string2)/max(strlen($word),strlen($string2) ) ) * 100;
$word . " - Percent match is: " . $percent[$word] . " </br>";
//60%
}

这个:

foreach ($words as $word) {
$percent[$word] = (1 - levenshtein($word, $string2)/max( strlen($word),strlen($string2) ) ) * 100;
}

然后将数组从大到小排序:

$percent = arsort($percent);

然后回显:

foreach ($percent as $key => $value) {
echo $key . " - Percent match is: " . $value . " </br>";
}

关于php - 查找与 2 个字符串最接近的百分比匹配,并返回下一个最接近的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46142149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com