我在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?
答案 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
)
在PlaceId
值上使用array_search
可能会更快,您可以使用array_column
进行访问:
if (($k = array_search(837, array_column($places, 'PlaceId'))) !== false) {
print_r($places[$k]);
}
else {
echo "Not found!";
}
答案 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]);