![](/img/trans.png)
[英]get the value of the key in an array in php without foreach loop and for loop
[英]PHP check array object key value without using loop/foreach
只是為了學習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;
}
}
但是有沒有一種方法可以在不使用循環的情況下進行檢查? 一種更有效的方式,因為我每次使用(大部分時間)都會感覺到這種方式,效率不是那么高,並且需要花費一些時間來處理。
如何將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
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.