PHP数组排序的相关性



我有一个PHP文本数组,它包含像"Blue Pencil, Blue Pen, Blue, Red Pencil, Red Ink, Red Pen, Blue Notebook, etc....">

我需要遍历每个数组项,并按照匹配相关度的顺序显示匹配结果。比如,如果用户搜索"Blue",然后是第三项"蓝色"完美匹配的应该列在最上面,然后是第二项"蓝色钢笔",然后是第一项"蓝色铅笔";最后是"蓝色笔记本"。其余所有非蓝色物品将被丢弃。

我尝试在PHP数组上使用sortrsort函数(在拉匹配蓝色项目之前和之后),但它们只是基于字母顺序和反向alpha列表进行排序。这里没有相关性匹配。例如使用sort($array)返回以下

Blue
Blue Notebook
Blue Pen
Blue Pencil

并不像预期的那样"相关"。结果。

levenshtein函数也不适合,因为它有一个限制,它在最大长度为255的字符串上工作。我的字符串可以更长。

为了绘制一个并行,MySQL有这个match-against子句来完成这项工作。

SELECT * , MATCH (col1, col2) AGAINST ('some words' IN NATURAL LANGUAGE MODE)

在PHP中寻找类似的东西,如果有人可以提供任何指针或任何UDF来编写。

全文搜索是一个复杂的主题。

array_filterusortlevenshtein组合在一起将得到您想要的这个特定查询的答案,但是您会发现,对于其他查询,它很快就崩溃了:


$data = explode(', ', 'Blue Pencil, Blue Pen, Blue, Red Pencil, Red Ink, Red Pen, Blue Notebook');
$query = 'Blue';
// Do an exact match first
$data = array_filter($data, fn ($s) => str_contains($s, $query));
// Sort by the Levenshtein distance from the $query
usort($data, fn($a, $b) => levenshtein($query, $a) - levenshtein($query, $b));
var_dump($data);
// Will print: 
// array(4) {
//    [0]=>
//   string(4) "Blue"
//   [1]=>
//   string(8) "Blue Pen"
//   [2]=>
//   string(11) "Blue Pencil"
//   [3]=>
//   string(13) "Blue Notebook"
// }

思考:

  • 如果用户使用不同的大写字母(完全匹配不起作用)会发生什么
  • 如果用户正在寻找"蓝色笔记本"怎么办?(你需要某种字符串标记)
  • 是否要删除/忽略某些单词?(如"the","a",等等)
  • 如果你有成千上万的单词要浏览,会发生什么?这个解决方案的性能不是很好。

你可能最终会发现你最终会找到一个真正的搜索引擎,比如Apache Lucene或Elasticsearch。

$input = [蓝色铅笔",蓝色钢笔",蓝色",红色铅笔",红色墨水",红色钢笔",蓝色笔记本">

);$ =结果preg_grep("/^蓝色/我,输入美元);print_r(结果)美元;

你需要一个排序函数

$data = array("Blue Pencil", "Blue Pen", "Blue", "Red Pencil", "Red Ink", "Red Pen", "Blue Notebook");
asort($data);
print_r($data);

输出
Array ( [2] => Blue [6] => Blue Notebook [1] => Blue Pen [0] => Blue Pencil [4] => Red Ink [5] => Red Pen [3] => Red Pencil )

最新更新