开发者

how to get JSON child items

I usually play with single level JSON like below...

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

Pretty basic, how do I pick off child items like in this google maps JSON. For example the latitiude

 {
    "results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Pkwy",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
    开发者_Python百科       "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"
 }


simple

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


You might want to check out Read a value from JSON using PHP , @Ignacio Vazquez-Abrams says

In PHP, JSON objects decode to objects, and arrays to arrays:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜