为了在PHP中学习更多技术,我在循环foreach中使用过,我想找到一些关于如何检查数组对象的方法。假设我们得到的结果如下:
Array
(
[0] =; stdClass Object
(
[gallery_id] => 38
[artist_id] => 58
[title] => Appearances
[description] => Appearances
[photo_file] =>
[status] => 1
[insert_timestamp] => 2014-08-07 03:27:23
[update_timestamp] => 2014-08-07 15:26:24
[url] => talents/58/photos/38/Appearances
[position] =>
)
[1] => stdClass Object
(
[gallery_id] => 36
[artist_id] => 58
[title] => Endorsements
[description] => Endorsements
[photo_file] =>
[status] => 1
[insert_timestamp] => 2014-08-07 03:17:28
[update_timestamp] => 2015-01-13 15:50:09
[url] => talents/58/photos/36/Endorsements
[position] => 1
)
[2] => stdClass Object
(
[gallery_id] => 34
[artist_id] => 58
[title] => Magazine Covers
[description] => Magazine Covers
[photo_file] =>
[status] => 1
[insert_timestamp] => 2014-08-07 02:54:27
[update_timestamp] => 2015-01-13 15:50:10
[url] => talents/58/photos/34/Magazine-Covers
[position] => 2
)
)
我知道我们可以做这样的事情来检查对象中的值:
$myFlag = 2;
foreach($objArr as $obj){
if($obj->position == $myFlag){
return true;
}
}
但有没有办法在不使用循环的情况下检查它?一种更有效的方式,因为我觉得每当我使用它(大多数时间)时,效率并不高,并且需要时间来处理。
答案 0 :(得分:2)
如何使用带闭包的array_filter。
$myFlag = 2;
$target = array_filter($objArr, function($elem) use($myFlag){
return $elem->position === $myFlag;
});
print_r($target);
结果是......
Array
(
[2] => stdClass Object
(
[gallery_id] => 34
[artist_id] => 58
[title] => Magazine Covers
[description] => Magazine Covers
[photo_file] =>
[status] => 1
[insert_timestamp] => 2014-08-07 02:54:27
[update_timestamp] => 2015-01-13 15:50:10
[url] => talents/58/photos/34/magazine-covers
[position] => 2
)
)