php - 得到满足条件的更深的元素
问题描述
"address_components": [
{
"long_name": "8",
"short_name": "8",
"types": [
"street_number"
]
},
{
"long_name": "Promenade",
"short_name": "Promenade",
"types": [
"route"
]
},
{
"long_name": "Cheltenham",
"short_name": "Cheltenham",
"types": [
"postal_town"
]
},
{
"long_name": "Gloucestershire",
"short_name": "Gloucestershire",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "England",
"short_name": "England",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "United Kingdom",
"short_name": "GB",
"types": [
"country",
"political"
]
},
{
"long_name": "GL50 1LR",
"short_name": "GL50 1LR",
"types": [
"postal_code"
]
}
],
需要获取postal_code的值,也就是long_name中types=postal_code的值。在 api 结果中,似乎类型本身就是一个数组。循环查找是一种不好的方法。array_search 也不起作用。有谁能够帮我。
解决方案
您可以使用array_filter
迭代数组而不循环:
$postal_code_arrays = array_filter($arr, function($a){
if(!isset($a['types'])) return false;
// Or you can use another condition. i.e: if array only contains postal code
if(in_array('postal_code', $a['types'])) {
return true;
}
return false;
});
这将返回仅包含数组中最后一个的数组:
[
[
"long_name" => "GL50 1LR",
"short_name" => "GL50 1LR",
"types" => [
"postal_code"
]
]
]
推荐阅读
- node.js - 从对象 ID 数组中查找用户详细信息
- asp.net-core - 如何更改 QueryFilter 运行时间?
- javascript - 使用 NavigationService 在反应组件之外的反应组件中导航、弹出、重置
- pytorch - DataLoader PyTorch 的参数张量无效
- ios - 如何检查刷新控件是否在其目标操作方法中刷新
- java - 执行 while 并尝试捕获卡在循环中以进行用户输入验证/异常处理
- c - 如何将参数传递给使用 libevent 创建的事件函数?
- flutter - 脚手架底部导航栏重叠正文内容。如何预防
- postgresql - 如何在 timestampz 列中插入 UTC 值
- c# - 查询不更新表