使用用户定义的比较函数搜索指针 in_array [英] Search needle in_array using a user-defined comparison function

查看:42
本文介绍了使用用户定义的比较函数搜索指针 in_array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在搜索关于这个问题的一些问题后,我只能找到 这个这个 但两者都不允许将参数(AKA 针)发送到搜索函数,而是使用预定义函数并使用 array_filter.

After searching some question on SO about this issue I could only found this and this but both do not allow sending argument (AKA needle) to the search function but using pre-defined function and using array_filter.

我搜索in_array 文档但没有找到.

I search in_array documentation but found none.

我想要类似的东西(如 usort 启用):

I want to have something like (as usort enable):

function uin_array($haystack, $needle, $compareFunc)

我设法用简单的 foreach 循环来实现它:

I manage to implement it with simple foreach loop:

function uin_array($haystack, $needle, $compareFunc) {
    foreach($haystack as $e) {
        if ($compareFunc($needle, $e) == 0)
            return true;
    }    
    return false;
}

示例:

$found = uin_array(["AA", "BB", "CC", "DD"], "cc", "strcasecmp");

这也可以用于多维数组中的搜索.

This could also be used in searching in the multi-dimension array.

我的问题:

在 PHP 中是否有任何我不知道的内置函数/标志?有没有更好的实现方式?

Is there any built-in function/flag like this in PHP that I'm not aware of? Is there any better way to implement it?

编辑:

我知道我可以使用 array_filter 作为:current(array_filter($haystack, function($element) use ($needle) { ... })) 但是在所有情况下是 O(n) - 在某些情况下使用 loop 和 break 或 in_array 可能是 O(1)(仅在最坏的情况下是 O(n),但不是全部)

I know I can use array_filter as: current(array_filter($haystack, function($element) use ($needle) { ... })) but that is O(n) in all cases - using loop and break or in_array may be O(1) in some case (will be O(n) in only in worst case but not all)

推荐答案

如果你不怕函数柯里化,可以看看 函数式 php 库.

If you are not afraid of function currying, take a look at functional-php library.

use function Functional\partial_any;
use function Functional\some;
use function Functional\placeholder;

$haystack = ["AA", "BB", "CC", "DD"];
$needle = "cc";
$compareFunc = "strcasecmp";

$found = some($haystack, partial_any($compareFunc, $needle, placeholder()));

该库提供了很好的助手来编写更多函数式的代码,但我建议你在整个项目中使用它或者根本不使用它,因为只需要一两次偶尔使用它不会很有道理.

The library provides nice helpers to write code in more functional style, but I would advice you to use it in the whole project or not to use it at all, because requiring it only for one or two occasional uses doesn't make a lot of sense.

这篇关于使用用户定义的比较函数搜索指针 in_array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆