我有一个字符串,其中包含一堆带有空格分隔符的单词,这些单词来 self 的数据库,另一个类似的字符串包含来自用户输入的单词。
$usrKeywords = 'test1 test4 test2'; //$_POST['keywords']
$dbKeywords = 'test1 test2 test3 test4 test5'; //from the DB
如何查看用户关键字与数据库关键字匹配的百分比?
所以对于上述情况,它将是 60%。
我知道我必须知道总共有多少个单词,然后检查 db 关键字字符串中包含多少匹配的用户关键字,然后像 3/5 * 100
这样获取百分比(对于上面的示例)。
但是在代码方面我不知道该怎么做。
最佳答案
您可以使用 array_intersect
function计算这个百分比:
$usrKeywords = 'test1 test4 test2'; //$_POST['keywords']
$dbKeywords = 'test1 test2 test3 test4 test5'; //from the DB
$arr1 = explode(' ', $usrKeywords);
$arr2 = explode(' ', $dbKeywords);
$aint = array_intersect($arr2, $arr1);
print_r($aint);
echo "percentage = " . (count($aint) * 100 / count($arr2)); // 60
关于php - 计算一串单词中匹配单词的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24486115/