繁体   English   中英

检查项目的分类数组的最快方法?

[英]Quickest way to check an array of classed for an item?

我有一个值类:

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [val] => one
        )
    [1] => stdClass Object
        (
            [id] => 2
            [val] => two
        )
    [2] => stdClass Object
        (
            [id] => 3
            [val] => three
        )
)

搜索此数组以查看是否存在id = 2的项的最快方法是什么? 我知道这会起作用:

$hasTwo = false;
foreach ($arrayItems as $arrayItem) {
    if ($arrayItem->id == 2) {
        $hasTwo = true;
        break;
    }
}

if ($hasTwo) {
    // do what I wanted to do...
}

没有更简单的方法需要更少的代码来完成相同的工作吗?

也许

$hasTwo = array_filter(
    $arrayItems,
    function($value) {
        return $value->id == 2;
    }
);

但是您需要测试哪个更快,答案可能是您的原始代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM