Php 是否可以在没有循环的情况下检查一个充满对象的数组中是否存在值?
我有一个包含多个对象的数组。是否可以在不循环的情况下检查任何一个对象(例如id->27)中是否存在值?与PHP的In_array()函数类似。谢谢Php 是否可以在没有循环的情况下检查一个充满对象的数组中是否存在值?,php,arrays,oop,Php,Arrays,Oop,我有一个包含多个对象的数组。是否可以在不循环的情况下检查任何一个对象(例如id->27)中是否存在值?与PHP的In_array()函数类似。谢谢 > array(10)[0]=>Object #673 ["id"]=>25 ["name"]=>spiderman [1]=>Object #674 ["id"]
> array(10)[0]=>Object #673
["id"]=>25
["name"]=>spiderman
[1]=>Object #674
["id"]=>26
["name"]=>superman
[2]=>Object #675
["id"]=>27
["name"]=>superman
.......
.......
.........
你可以做:
foreach ($array as $value)
{
if ($value == "what you are looking for")
break;
}
-在数组中搜索给定值并返回
如果成功,则对应密钥
不需要。如果您经常需要快速直接查找值,则需要使用数组键进行查找,这非常快。例如:
// prepare once
$indexed = array();
foreach ($array as $object) {
$indexed[$object->id] = $object;
}
// lookup often
if (isset($indexed[42])) {
// object with id 42 exists...
}
如果您需要通过不同的键查找对象,因此无法真正通过一个特定的键对其进行索引,那么您需要研究不同的搜索策略,例如。您需要以某种方式进行循环,但您不必自己手动实现循环。看一看。您只需提供一个检查对象的函数,如下所示:
function checkID($var)
{
return $var->id == 27;
}
if(count(array_filter($input_array, "checkID")) {
// you have at least one matching element
}
或者您甚至可以在一行中完成此操作:
if(count(array_filter($input_array, function($var) { return $var->id == 27; })) {
// you have at least one matching element
}
您可能希望组合两个函数以获得所需的结果 数组搜索($pinder,array\u column($array,'key\u field') 创建了一个小代码来演示它的使用
<?php
$superheroes = [
[
"id" => 1,
"name" => "spiderman"
],
[
"id" => 2,
"name" => "superman"
],
[
"id" => 3,
"name" => "batman"
],
[
"id" => 4,
"name" => "robin"
],
];
$needle = 'spiderman';
$index = array_search($needle, array_column($superheroes, "name"));
echo "Is $needle a superhero?<br/>";
//Comparing it like this is important because if the element is found at index 0,
//array_search will return 0 which means false. Hence compare it with !== operator
if ( false !== $index ) {
echo "yes";
} else {
echo "no";
}
?>
虽然这是一个很好的函数,但它对OP不起作用,因为他需要检查数组值中的一个字段,而不是值本身-而且数组搜索
不接受您所说的不循环遍历整个数组的比较函数。这是真的。我会适当更改。不要使用!empty($var)
当你只是指$var
时。这可能是非常浪费的,因为一旦找到值,它不会中断,但总是遍历所有值。@deceze同意。问题是他的数组有多大。如果他处理数百万项,这将不好。如果数组只包含少数项(甚至几百项),影响可以忽略不计。empty
对函数返回值不起作用,在这里也不需要使用它。纯布尔比较很好。@deceze我知道。我不确定那里发生了什么:我以前编辑过我的帖子,删除了empty
,但它重新出现了。我重新编辑了。
$results = array_filter($array, function($item){
return ($item->id === 27);
});
if ($results)
{
.. You have matches
}
<?php
$superheroes = [
[
"id" => 1,
"name" => "spiderman"
],
[
"id" => 2,
"name" => "superman"
],
[
"id" => 3,
"name" => "batman"
],
[
"id" => 4,
"name" => "robin"
],
];
$needle = 'spiderman';
$index = array_search($needle, array_column($superheroes, "name"));
echo "Is $needle a superhero?<br/>";
//Comparing it like this is important because if the element is found at index 0,
//array_search will return 0 which means false. Hence compare it with !== operator
if ( false !== $index ) {
echo "yes";
} else {
echo "no";
}
?>