【问题标题】:Google API JSON Postal Code with PHP in Address Object地址对象中带有 PHP 的 Google API JSON 邮政编码
【发布时间】:2014-02-22 19:49:21
【问题描述】:

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

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

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

【问题讨论】:

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


【解决方案1】:

如果您想检索邮政编码,这应该对您有用。它应该让您了解如何访问所需的其他数据:

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

【讨论】:

    【解决方案2】:

    只是对 Springie 提供的答案的一点补充。如果你想遍历整个数组,你需要添加另一个条件,因为你最终可能只得到邮政编码的前缀。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 2018-11-02
      • 2020-06-05
      • 1970-01-01
      • 2018-10-17
      相关资源
      最近更新 更多