"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值,该值是type = postal_code的long_name值。在api结果中,类型本身似乎是一个数组。循环查找是一种不好的方法。同样array_search也不能正常工作。有人可以帮我吗?
答案 0 :(得分:2)
只需遍历数组并找到具有邮政编码的项目:
foreach ($arr["address_components"] as $item) {
if (in_array("postal_code", $item["types"])) {
echo $item["long_name"];
}
}
我将把错误处理留给您。
答案 1 :(得分:2)
您可以使用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"
]
]
]
答案 2 :(得分:0)
尝试使用array_filter
$postCode = array_filter($arr["address_components"], function($v) {
return in_array("postal_code", $v["types"]);
})[0]['long_name'];