All I want is the value long_name for the listing with type postal_code. It's on a different array ID on each address variation otherwise I would have just used semething like this:
$jsonobj->results[0]->address_components[2]->long_name;
That won't work though ;(
This is the code, from the Google GEO location API
{
"results" : [
{
"address_components" : [
{
"long_name" : "2565",
"short_name" : "2565",
"types" : [ "postal_code", "postal_code_prefix" ]
},
{
"long_name" : "Den Haag",
"short_name" : "Den Haag",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Den Haag",
"short_name" : "Den Haag",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Zuid-Holland",
"short_name" : "ZH",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Nederland",
"short_name" : "NL",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "2565 Den Haag, Nederland",
"geometry" : {
"bounds" : {
...
So, in short, how can i get the "long_name" value for "types == postal_code" (maybe with in_array(postal_code, $types)?).
Answer already given but wanted to post my version of the function here as well:
$city = getAddressDetail($jsonobj, 'locality');
$zipcode = getAddressDetail($jsonobj, 'postal_code');
function getAddressDetail($jsonobj, $attr){
// Loop over each result
foreach ($jsonobj->results as $result) {
// Loop over each address_component of a given result
foreach ($result->address_components as $component) {
// Check for 'postal_code' in the types array
if (in_array($attr, $component->types, true)) {
// Extract the 'long_name'
return $component->long_name;
}
}
}
}
json_decode($jsonobj, true)to turn the data from json into an array?$jsonobj->results[0]->address_componentsand for each value it will check if types contains the value postal_code. If it does then you take the long_name value from that element and return it.