如何获取JSON子项

时间:2011-08-27 20:33:54

标签: php google-maps

我通常使用下面的单级JSON ...

 <?php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>

非常基本,如何选择像谷歌地图JSON中的子项目。例如latitiude

 {
    "results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Pkwy",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "San Jose",
           "short_name" : "San Jose",
           "types" : [ "administrative_area_level_3", "political" ]
        },
        {
           "long_name" : "Santa Clara",
           "short_name" : "Santa Clara",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4220110,
           "lng" : -122.08406610
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.42335998029150,
              "lng" : -122.0827171197085
           },
           "southwest" : {
              "lat" : 37.42066201970850,
              "lng" : -122.0854150802915
           }
        }
     },
     "types" : [ "street_address" ]
  }
    ],
    "status" : "OK"
 }

2 个答案:

答案 0 :(得分:0)

你可能想看看Read a value from JSON using PHP,@ Ignacio Vazquez-Abrams说

  

在PHP中,JSON对象解码为对象,数组解码为数组:

   $data->results[0]->geometry->location->lat
   $data->results[0]->geometry->location->lng

答案 1 :(得分:0)

简单

$json = json_decode($json);
echo $json->results[0]->geometry->location->lat;