地址对象中带有PHP的Google API JSON邮政编码

地址对象中带有PHP的Google API JSON邮政编码,php,json,google-maps-api-3,Php,Json,Google Maps Api 3,我想从JSON返回中获取地址详细信息,如: 但是数组的元素数量总是不同的。因此,您知道如何使用php获取地址详细信息(如邮政编码)吗?如果您想检索邮政编码,这应该适用于您。它应该让您了解如何访问所需的其他数据: // Decode json $decoded_json = json_decode($json); foreach($decoded_json->results as $results) { foreach($results->address_componen

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


但是数组的元素数量总是不同的。因此,您知道如何使用php获取地址详细信息(如邮政编码)吗?

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

// 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提供的答案稍加补充。如果要在整个数组中循环,则需要添加另一个条件,因为最终可能只得到post代码的前缀

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

遍历数组,查找type='postal_code',但我会从最后一个元素开始,然后更快速地查找它