使用自定义比较器在 PHP 数组中搜索 [英] Search in PHP array with a custom comparator

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

问题描述

这可能是无望的,但是,有没有办法用我自己的比较器函数搜索数组中的元素?在 PHP 中实现它会导致搜索缓慢,所以也许存在更好的解决方案?

This is probably hopeless but still, is there a way to search for elements in an array with my own comparator function? Implementing it in PHP would result in slow searches, so maybe a better solution exists?

我真正想从搜索中得到的是 a) 了解该元素是否存在于数组中,以及 b) 最好是获取找到的元素的键(索引).

What I actually want from the search is a) get to know whether the element is present in the array and b) preferably, get the key (index) of the found element.

例如

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

如果比较器看起来像这样

and if the comparator would look like this

$comp = function ($arrValue, $findValue) {
    return ($arrValue % $findValue) == 0;
};

如果 8 被搜索,那么基于比较器的搜索函数将返回 true 并且,这会很好,输出找到的元素的索引,即7.

Then the comparator-based search function would return true if 8 was searched and, which would be nice of it, output the index of the found element, which is 7.

推荐答案

你的意思是:

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$findValue = 8;

$result = array_filter(
    $arr, 
    function ($arrValue) use($findValue) {
        return ($arrValue % $findValue) == 0;
    }
);

编辑

也许你的意思更像是:

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$findValue = 3;

foreach(array_filter(
    $arr, 
    function ($arrValue) use($findValue) {
        return ($arrValue % $findValue) == 0;
    }
) as $key => $value) {
    echo $value, ' is a multiple of ', $findValue, PHP_EOL;
}

编辑 #2

或者你的意思是更复杂的东西,比如:

Or do you mean something a lot more sophisticated like:

function filter($values, $function) {
    return array_filter(
        $values,
        $function
    );
}

$isEven = function ($value) {
    return !($value & 1);
};

$isOdd = function ($value) {
    return $value & 1;
};

$data = range(1,10);

echo 'array_filter() for Odds', PHP_EOL;
var_dump(
    filter(
        $data,
        $isOdd
    )
);

echo 'array_filter() for Evens', PHP_EOL;
var_dump(
    filter(
        $data,
        $isEven
    )
);

或者也使用 PHP 5.5 生成器:

or using PHP 5.5 Generators as well:

$isEven = function ($value) {
    return !($value & 1);
};

$isOdd = function ($value) {
    return $value & 1;
};

function xFilter(callable $callback, $args=array()) {
    foreach($args as $arg) {
        if (call_user_func($callback, $arg)) {
            yield $arg;
        }
    }
}

echo 'xFilter for Odds', PHP_EOL;
foreach(xFilter($isOdd, range(1,10)) as $i) {
    echo('num is: '.$i.PHP_EOL);
}

echo 'xFilter for Evens', PHP_EOL;
foreach(xFilter($isEven, range(1,10)) as $i) {
    echo('num is: '.$i.PHP_EOL);
}

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

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