使用Google地图解码PHP中的API响应

I'm struggling to get the "Adams County" from "administrative_area_level_2" type from this api response http://maps.googleapis.com/maps/api/geocode/json?latlng=39.76144296429947,-104.8011589050293&sensor=false .

I simply need to output the county based on the latitude and longitude.

$query = @unserialize(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=39.76144296429947,-104.8011589050293&sensor=false'));
echo 'Hello visitor from '.$query["response"];

This is what I have for now. Thank you.

Use json_decode instead of unserialize, as the response is in JSON format.

Then just iterate the items in a loop or two, for example:

$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=39.76144296429947,-104.8011589050293&sensor=false'; $response = json_decode(file_get_contents($url), true);
if (empty($response['results'])) {
  // handle error
}

$long_name = null;

foreach ($response['results'] as $r) {
  if (empty($r['address_components']) || empty($r['types']))
    continue;


  if (array_search('administrative_area_level_2', $r['types']) === false)
    continue;

  foreach ($r['address_components'] as $ac) {
    if (array_search('administrative_area_level_2', $ac['types']) !== false) {
      $long_name = $ac['long_name'];
      break;
    }
  }
}

echo $long_name;

Output

Adams County

You will need to use a recursive search and keep track of the previous found item in the result array.

$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=39.76144296429947,-104.8011589050293&sensor=false';
$query = @json_decode(file_get_contents($url),true);


$address_components = $query['results'][0]['address_components'];

array_walk_recursive( $address_components,
                  function($item, $key) use(&$prev_item, &$stop){ 
                        if($item == 'administrative_area_level_2'){ 
                            $stop = true;
                        }
                        else {
                            if(!$stop)
                                $prev_item = $item; 
                        }
                  });

var_dump($prev_item);