【发布时间】:2019-09-08 08:51:00
【问题描述】:
我正在创建一个单词搜索,但我想根据搜索关键字的最高存在对它们进行排名。我正在尝试搜索数组 1 键是否存在于数组 2 长字符串中,然后按数组 2 中数组 1 的总出现次数对数组进行排序。
输入示例:
$arr = array(array("id" => 1,"title" => "Hello World", "body" => "Hi Jude All this is my content"),
array("id" => 2,"title" => "Hello World Boy", "body" => "Hi All this is my content Girl"),
array("id" => 3,"title" => "Hello Kids", "body" => "Hi All this is my content Kid"),
array("id" => 4,"title" => "Hello World Jude", "body" => "Hi All this is my content Jude"),
array("id" => 5,"title" => "Hello World Jude January", "body" => "Hi All this is my content Jan"),
array("id" => 6,"title" => "Hello World January June Lord", "body" => "Hi All this is my content Jan Jude Lord"));
$str = "Hello world January jude";
愿望输出:
按顺序排列:
Hello World Jude January
Hello World Jude
Hello World January June Lord
Hello World
Hello World Boy
Hello Kids
我之前写了一个问题,基于解决Is there any PHP function to solve out array value matches in another array value string? 的问题,后来我得到了解决方案,但我现在的主要问题是如果我的搜索关键字是,它会根据 区分大小写 来判断我的过滤器hello world 和我有 Hello world 和 hi world 因为hi world 上的世界是小写的,因为我的搜索关键字中它会先选择小写字母,然后再考虑匹配最多的那个我尝试了几件事但我无法得到它。
注意:我希望以不以小写格式返回的方式返回输出。
这是我尝试使用上面的示例输入:
$arr2 = sort_most_exists_asc($arr, $str);
var_dump($arr2);
function sort_most_exists_asc($array, $str) {
usort($array, function ($a, $b) use ($str) {
$aa = count(array_intersect(explode(" ", $str), explode(" ", $a['title'])));
$bb = count(array_intersect(explode(" ", $str), explode(" ", $b['title'])));
return $bb - $aa;
});
return $array;
}
如果它的格式完全一样,效果很好,但我不希望它在 array_intersect 期间遵循区分大小写。
【问题讨论】:
-
@dWinder #dWinder
-
请帮忙?我正在使用它来搜索数据库中的数据并根据最佳结果匹配提供输出。
-
您的代码运行良好...3v4l.org/MmlNc
-
没有我的代码是在区分大小写之后,在单词最现有检查之前我希望它忽略单词大小写敏感性并使用数组中存在的大多数来为我排序。
-
而且效果很好——如果你看一下我的演示,我已经将
$str中的所有单词都设为小写,但数组仍然会被排序,就好像它们仍然有第一个字母大写一样
标签: php arrays algorithm sorting