地址对象中使用PHP的Google API JSON邮政编码

时间:2014-01-30 13:19:59

标签: php json google-maps-api-3

我想从JSON返回获取地址详细信息,如:

http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false

但是数组的元素数量总是不同的。那么任何想法如何使用php获取地址代码等地址详细信息?

2 个答案:

答案 0 :(得分:2)

如果您想要检索postal_code,这应该适合您。它应该让您了解如何访问您需要的其他数据:

// 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;            
        }
    }
}

答案 1 :(得分:0)

只是 Springie 提供的答案的补充。如果要遍历整个数组,则需要添加其他条件,因为您可能最终只会获得邮政编码的前缀。

if ( isset($address_components->types) 
    && $address_components->types[0] === 'postal_code'
    && !in_array('postal_code_prefix', $address_components->types) ) { }