3
votes

I want go get the adress details from a JSON return like:

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

But the Array always differs in the amount of elements. So any Idea how to get the adress details like postal code with php?

2
Iterate through the array, looking for types='postal_code', but I would start with the last element and work up to find it more quickly.James Black

2 Answers

4
votes

This should work for you if you want to retrieve the postal_code. It should give you the idea of how to access the other data you require:

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

Just a little addition to the answer provided by Springie. If you want to loop through the whole array, you'll need to add another condition, because you might end up with getting only prefix of the post code.

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