【发布时间】:2014-02-22 19:49:21
【问题描述】:
我想从 JSON 返回中获取地址详细信息,例如:
但是数组的元素数量总是不同的。那么任何想法如何使用php获取邮政编码等地址详细信息?
【问题讨论】:
-
遍历数组,寻找 types='postal_code',但我会从最后一个元素开始,并努力更快地找到它。
标签: php json google-maps-api-3
我想从 JSON 返回中获取地址详细信息,例如:
但是数组的元素数量总是不同的。那么任何想法如何使用php获取邮政编码等地址详细信息?
【问题讨论】:
标签: php json google-maps-api-3
如果您想检索邮政编码,这应该对您有用。它应该让您了解如何访问所需的其他数据:
// Decode json
$decoded_json = json_decode($json);
foreach($decoded_json->results as $results)
{
foreach($results->address_components as $address_components)
{
// Check types is set then get first element (may want to loop through this to be safe,
// rather than getting the first element all the time)
if(isset($address_components->types) && $address_components->types[0] == 'postal_code')
{
// Do what you want with data here
echo $address_components->long_name;
}
}
}
【讨论】:
只是对 Springie 提供的答案的一点补充。如果你想遍历整个数组,你需要添加另一个条件,因为你最终可能只得到邮政编码的前缀。
if ( isset($address_components->types)
&& $address_components->types[0] === 'postal_code'
&& !in_array('postal_code_prefix', $address_components->types) ) { }
【讨论】: