在PHP对象数组中按值查找对象

时间:2019-04-18 00:51:31

标签: php arrays

我在PHP中有一个对象数组,如下所示:

[Places] => Array
    (
        [0] => stdClass Object
            (
                [PlaceId] => 837
                [Name] => United Arab Emirates
                [Type] => Country
            )

        [1] => stdClass Object
            (
                [PlaceId] => 838
                [Name] => Afghanistan
                [Type] => Country
            )

        [2] => stdClass Object
            (
                [PlaceId] => 839
                [Name] => Antigua and Barbuda
                [Type] => Country
            )
    )

如果仅知道PlaceId的值(例如837),如何在此数组内检索Object?

2 个答案:

答案 0 :(得分:2)

一个简单的foreach循环就可以完成工作:

foreach ($places as $place) {
    if ($place->PlaceId == 837) break;
}
if ($place->PlaceId == 837) 
    print_r($place);
else
    echo "Not found!";

输出:

stdClass Object
    (
         [PlaceId] => 837
         [Name] => United Arab Emirates
         [Type] => Country
    )

Demo on 3v4l.org

PlaceId值上使用array_search可能会更快,您可以使用array_column进行访问:

if (($k = array_search(837, array_column($places, 'PlaceId'))) !== false) {
    print_r($places[$k]);
}
else {
    echo "Not found!";
}

Demo on 3v4l.org

答案 1 :(得分:0)

使用{% block content %} {% for cat in category %} <div class="row"> <div class="bg-success rounded-top border border-dark" style="width:100%; padding-left:8px;"> {{cat.cat_name}} </div> </div> <div class="row"> <div class="bg-secondary border border-dark" style="width:100%; padding-left:16px;"> Forums_Go_Here </div> </div> {% endfor %} {% endblock content %} array_search

array_column()

输出:

$key = array_search(839, array_column($places['Places'], 'PlaceId'));
print_r($places['Places'][$key]);

演示: https://3v4l.org/RsPr4