搜索这个json数组的有效方法?

时间:2012-08-01 19:20:09

标签: php arrays json

我的程序员在从这个json数组中获取location数据(纬度和经度)时遇到问题。 foreach循环会找到location:的纬度/经度并回显它们会是什么?感谢

$jsonArray = json_decode($jsondata, true);

$jsondata =  {
       "results" : [
          {
             "address_components" : [
                {
                   "long_name" : "2340",
                   "short_name" : "2340",
                   "types" : [ "postal_code" ]
                },
                {
                   "long_name" : "New South Wales",
                   "short_name" : "NSW",
                   "types" : [ "administrative_area_level_1", "political" ]
                },
                {
                   "long_name" : "Australia",
                   "short_name" : "AU",
                   "types" : [ "country", "political" ]
                }
             ],
             "formatted_address" : "New South Wales 2340, Australia",
             "geometry" : {
                "bounds" : {
                   "northeast" : {
                      "lat" : -30.79897870,
                      "lng" : 151.394080
                   },
                   "southwest" : {
                      "lat" : -31.661670,
                      "lng" : 150.334880
                   }
                },
                "location" : {
                   "lat" : -31.28146910,
                   "lng" : 151.04713550
                },
                "location_type" : "APPROXIMATE",
                "viewport" : {
                   "northeast" : {
                      "lat" : -30.79897870,
                      "lng" : 151.394080
                   },
                   "southwest" : {
                      "lat" : -31.661670,
                      "lng" : 150.334880
                   }
                }
             },
             "types" : [ "postal_code" ]
          }
       ],
       "status" : "OK"
    };

1 个答案:

答案 0 :(得分:3)

为什么需要循环?您可以直接使用以下方式访问它:

echo $jsonArray['results'][0]['geometry']['location']['lat'];

有多个结果,它将是

foreach( $jsonArray['results'] as $row) { 
    $lat = $row['geometry']['location']['lat'];
    $long = $row['geometry']['location']['lng'];
    echo $lat . ' ' . $long . "\n";
}