是否可以在没有循环的情况下检查一个满是对象的数组中是否存在值?

Stu*_*Stu 5 php arrays oop

我有一个包含多个对象的数组.是否可以检查任何一个对象中是否存在值,例如id-> 27 而没有循环?以类似于PHP的in_array()函数的方式.谢谢.

> array(10)[0]=>Object #673 
                     ["id"]=>25 
                     ["name"]=>spiderman   
           [1]=>Object #674
                     ["id"]=>26
                     ["name"]=>superman   
           [2]=>Object #675
                     ["id"]=>27
                     ["name"]=>superman 
           ....... 
           .......
           .........
Run Code Online (Sandbox Code Playgroud)

dec*_*eze 6

不。如果您经常需要快速直接查找值,则需要为它们使用数组键,查找速度快如闪电。例如:

// prepare once
$indexed = array();
foreach ($array as $object) {
    $indexed[$object->id] = $object;
}

// lookup often
if (isset($indexed[42])) {
    // object with id 42 exists...
}
Run Code Online (Sandbox Code Playgroud)

如果您需要通过不同的键查找对象,因此您无法真正通过一个特定的键对它们进行索引,则需要研究不同的搜索策略,例如binary search 。


Ale*_*s G 5

您将需要以一种或另一种方式进行循环 - 但您不必自己手动实现循环。看看array_filter函数。您需要做的就是提供一个检查对象的函数,如下所示:

function checkID($var)
{
    return $var->id == 27;
}

if(count(array_filter($input_array, "checkID"))) {
    // you have at least one matching element
}
Run Code Online (Sandbox Code Playgroud)

或者你甚至可以在一行中完成此操作:

if(count(array_filter($input_array, function($var) { return $var->id == 27; }))) {
    // you have at least one matching element
}
Run Code Online (Sandbox Code Playgroud)


Lee*_*vis 5

$results = array_filter($array, function($item){
   return ($item->id === 27);
});
if ($results)
{
   ..  You have matches
}
Run Code Online (Sandbox Code Playgroud)