I want go get the adress details from a JSON return like:
But the Array always differs in the amount of elements. So any Idea how to get the adress details like postal code with php?
I want go get the adress details from a JSON return like:
But the Array always differs in the amount of elements. So any Idea how to get the adress details like postal code with php?
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;
}
}
}
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) ) { }