本文介绍了如何根据与输入单词的相似度对数组进行排序.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有关于 PHP 数组,例如:
I have on PHP array, for example:
$arr = array("hello", "try", "hel", "hey hello");
现在我想根据数组和 $search var 之间最接近的单词重新排列数组.
Now I want to do rearrange of the array which will be based on the most nearly close words between the array and my $search var.
我该怎么做?
推荐答案
这是一个使用 http://php.net/manual/en/function.similar-text.php:
这会计算两个字符串之间的相似度,如编程经典:Oliver 的《实现世界上最好的算法》(ISBN 0-131-00413-1)中所述.请注意,此实现不像 Oliver 的伪代码那样使用堆栈,而是使用递归调用,这可能会或可能不会加速整个过程.另请注意,该算法的复杂度为 O(N**3),其中 N 是最长字符串的长度.
$userInput = 'Bradley123';
$list = array('Bob', 'Brad', 'Britney');
usort($list, function ($a, $b) use ($userInput) {
similar_text($userInput, $a, $percentA);
similar_text($userInput, $b, $percentB);
return $percentA === $percentB ? 0 : ($percentA > $percentB ? -1 : 1);
});
var_dump($list); //output: array("Brad", "Britney", "Bob");
或者使用 http://php.net/manual/en/function.levenshtein.php:
Levenshtein 距离定义为将 str1 转换为 str2 时必须替换、插入或删除的最少字符数.该算法的复杂度为O(m*n),其中n和m分别为str1和str2的长度(与similar_text()相比相当不错,为O(max(n,m)**3),但还是贵).
$userInput = 'Bradley123';
$list = array('Bob', 'Brad', 'Britney');
usort($list, function ($a, $b) use ($userInput) {
$levA = levenshtein($userInput, $a);
$levB = levenshtein($userInput, $b);
return $levA === $levB ? 0 : ($levA > $levB ? 1 : -1);
});
var_dump($list); //output: array("Britney", "Brad", "Bob");
这篇关于如何根据与输入单词的相似度对数组进行排序.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!