访问JSON数组PHP中的值

时间:2013-06-20 01:17:28

标签: php json

我没有成功从JSON数组对象中获取值。我特意尝试使用geometry-> location-> lat

这是我正在做的事情:

    $url='http://maps.googleapis.com/maps/api/geocode/json?address='.$a.'&sensor=false';
    $result = file_get_contents($url);
    $jsonArr = json_decode($result,true);

    echo "Lat: ".$jsonArr['results']['geometry']['location']['lat'];

以下是Google返回的JSON的print_r():

 {
       "results" : [
          {
             "address_components" : [
                {
                   "long_name" : "46814",
                   "short_name" : "46814",
                   "types" : [ "postal_code" ]
                },
                {
                   "long_name" : "Fort Wayne",
                   "short_name" : "Fort Wayne",
                   "types" : [ "locality", "political" ]
                },
                {
                   "long_name" : "Indiana",
                   "short_name" : "IN",
                   "types" : [ "administrative_area_level_1", "political" ]
                },
                {
                   "long_name" : "United States",
                   "short_name" : "US",
                   "types" : [ "country", "political" ]
                }
             ],
             "formatted_address" : "Fort Wayne, IN 46814, USA",
             "geometry" : {
                "bounds" : {
                   "northeast" : {
                      "lat" : 41.08472709999999,
                      "lng" : -85.26534090
                   },
                   "southwest" : {
                      "lat" : 41.00163510,
                      "lng" : -85.35540899999999
                   }
                },
                "location" : {
                   "lat" : 41.05472940,
                   "lng" : -85.30328109999999
                },
                "location_type" : "APPROXIMATE",
                "viewport" : {
                   "northeast" : {
                      "lat" : 41.08472709999999,
                      "lng" : -85.26534090
                   },
                   "southwest" : {
                      "lat" : 41.00163510,
                      "lng" : -85.35540899999999
                   }
                }
             },
             "types" : [ "postal_code" ]
          }
       ],
       "status" : "OK"
    }

1 个答案:

答案 0 :(得分:2)

结果以数组形式返回。获得第一个元素,你就完成了。但是,您应该确保结果数组中至少有一个元素。

echo "Lat: " . $jsonArr['results'][0]['geometry']['location']['lat'];