php - 是否有任何 PHP 函数可以通过不区分大小写的比较来解决另一个数组值字符串中的数组值匹配?

标签 php arrays algorithm sorting

我正在创建一个词搜索,但我想根据搜索关键字的最高存在对它们进行排名。我正在尝试搜索数组 1 键是否存在于数组 2 长字符串中,然后按数组 1 在数组 2 中的总出现次数对数组进行排序。

示例输入:

$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,它会根据 case sensitivity 判断我的过滤器worldhi world 因为 hi world 上的 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 期间区分大小写。

最佳答案

为可能需要进一步帮助的人解决了这里的问题 https://3v4l.org/tlvbh .

我使用 array-uintersect 解决了这个问题- 可以将函数作为参数进行比较。我送strcasecmp - 避免字符串比较中区分大小写。

这是我的新排序函数:

function sort_most_exists_asc($array, $str) {
    usort($array, function ($a, $b) use ($str) {
        $aa = count(array_uintersect(explode(" ", $str), explode(" ", $a['title']), 'strcasecmp'));
        $bb = count(array_uintersect(explode(" ", $str), explode(" ", $b['title']), 'strcasecmp'));
        return $bb - $aa;
    });
    return $array;
}

关于php - 是否有任何 PHP 函数可以通过不区分大小写的比较来解决另一个数组值字符串中的数组值匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55738873/

相关文章:

php - 从 OO PHP 中的重写方法中调用重写方法

c - 递归C图像压缩算法

c# - 按其包含的项目对项目进行分组

algorithm - 只遍历无向图的所有边一次

php - 将图像 url 替换为 img 标签

php - YouTube Analytics(分析)API:在 channel 上查找唯一身份访问者

php - 如何在 cURL POST 请求中使用数组

Python-从txt创建数组

c++ - 在 C++ 中编译模板结构

python - 对 numpy 数组进行子采样/平均