Php 谷歌地图地理编码结果顺序
我正在使用谷歌地图地理编码API发送部分地址和接收完整地址信息 谷歌的API在返回结果的方式上是不一致的,它基于给定的部分地址能够匹配的数据,特别是“地址组件”字段中的对象数(例如:有时它不包括“行政区域级别2”,在本例中为“国王县”) 我是否可以使用“类型”字段作为标识符来检索特定的“地址\组件”数据?否则,我似乎必须执行一系列的手动检查,以确定Google返回了多少address_组件,以及这些组件到底是什么 我感兴趣的JSON响应部分是:Php 谷歌地图地理编码结果顺序,php,json,google-maps-api-3,Php,Json,Google Maps Api 3,我正在使用谷歌地图地理编码API发送部分地址和接收完整地址信息 谷歌的API在返回结果的方式上是不一致的,它基于给定的部分地址能够匹配的数据,特别是“地址组件”字段中的对象数(例如:有时它不包括“行政区域级别2”,在本例中为“国王县”) 我是否可以使用“类型”字段作为标识符来检索特定的“地址\组件”数据?否则,我似乎必须执行一系列的手动检查,以确定Google返回了多少address_组件,以及这些组件到底是什么 我感兴趣的JSON响应部分是: { "results":[ {
{
"results":[
{
"address_components":[
{
"long_name":"125",
"short_name":"125",
"types":[
"street_number"
]
},
{
"long_name":"Court Street",
"short_name":"Court St",
"types":[
"route"
]
},
{
"long_name":"Brooklyn",
"short_name":"Brooklyn",
"types":[
"political",
"sublocality",
"sublocality_level_1"
]
},
{
"long_name":"Kings County",
"short_name":"Kings County",
"types":[
"administrative_area_level_2",
"political"
]
},
{
"long_name":"New York",
"short_name":"NY",
"types":[
"administrative_area_level_1",
"political"
]
},
{
"long_name":"United States",
"short_name":"US",
"types":[
"country",
"political"
]
},
{
"long_name":"11201",
"short_name":"11201",
"types":[
"postal_code"
]
}
],
非常感谢。您可以编写一个函数来检索给定类型的组件对象。大概是这样的:
$components = ...; // The JSON decoded "address_components" array
/**
* Get a component by type.
*
* @param {string} $type The component type. E.g. 'street_number'.
* @return {null|object} The desired component or null in case there's no
* component for the given type.
*/
$componentByType = function ($type) use ($components) {
$found = array_filter($components, function ($component) use ($type) {
return in_array($type, $component->types);
});
return reset($found);
};
使用您问题的回答,以下代码
$component = $componentByType('route');
echo $component->long_name;
。。。将输出:
法院街
<?php
$addr = json_decode('{json here..}', true);
/**
* @param string $name
* @param string $type
* @param array $from
* @return string|array|null
*/
function getByType($name, $type, array $from)
{
foreach($from as $values) {
if (in_array($type, $values['types'])) {
return $values[$name] ?: $values;
}
}
return null;
}
var_dump(getByType('long_name', 'route', $addr['results'][0]['address_components']));