2016-10-25 7 views
-2

私はこの「apache」の応答 http://maps.googleapis.com/maps/api/geocode/json?latlng=39.76144296429947,-104.8011589050293&sensor=falseから「administrative_area_level_2」タイプ を取得するのに苦労しています。GoogleマップのPHPのAPIの応答をデコード

緯度と経度に基づいて郡を出力するだけです。

$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"]; 

これは私が今持っているものです。ありがとうございました。

+0

出力がJSONのように見えるので、代わりに '' unserialize' –

+0

@RuslanOsmanovのあなたは正しいが、どのように私はLONG​​_NAME」の値を取得します(真、のfile_get_contents(...)) 'json_decodeを使用"" administrative_area_level_2 "タイプのコードの"これは私の問題です.. –

答えて

0

unserializeの代わりにを使用してください(レスポンスはJSON形式です)。

は、それからちょうど例えば、ループまたは2内の項目を反復:

$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; 

出力

Adams County 
2

あなたは再帰的な検索を使用して見つかった、前のトラックを保持する必要があります。結果配列内のitem

$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); 
関連する問題