2014-09-26 84 views
1

當轉換爲PHP數組(不是stdClass對象)時,如何才能訪問幾何位置到lat和long?我試過$ data ['results'] ['geometry'] ['location'] ['lat']和['lng']但它沒有奏效。訪問PHP數組中的鍵值對

我是越來越未定義,偏移量和不能使用字符串作爲陣列偏移等

{ 
    "results" : [ 
     { 
     "address_components" : [ 
      { 
       "long_name" : "1600", 
       "short_name" : "1600", 
       "types" : [ "street_number" ] 
      }, 
      { 
       "long_name" : "Amphitheatre Parkway", 
       "short_name" : "Amphitheatre Pkwy", 
       "types" : [ "route" ] 
      }, 
      { 
       "long_name" : "Mountain View", 
       "short_name" : "Mountain View", 
       "types" : [ "locality", "political" ] 
      }, 
      { 
       "long_name" : "Santa Clara County", 
       "short_name" : "Santa Clara County", 
       "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 Parkway, Mountain View, CA 94043, USA", 
     "geometry" : { 
      "location" : { 
       "lat" : 37.4222953, 
       "lng" : -122.0840671 
      }, 
      "location_type" : "ROOFTOP", 
      "viewport" : { 
       "northeast" : { 
        "lat" : 37.42364428029151, 
        "lng" : -122.0827181197085 
       }, 
       "southwest" : { 
        "lat" : 37.42094631970851, 
        "lng" : -122.0854160802915 
       } 
      } 
     }, 
     "types" : [ "street_address" ] 
     } 
    ], 
    "status" : "OK" 
} 

回答

3

$data['results']是索引數組。你只需要修復您是如何訪問它:

$data['results'][0]['geometry']['location']['lat'] 
+1

+1:嗯,我是太慢了:P – nem035 2014-09-26 20:55:44

+0

呵呵。我也是,nem ;-) – 2014-09-26 20:56:21

+0

沒問題,樂於幫忙! @恩對不起! :P – 2014-09-26 21:01:52

0

你的道:

$data['results']['geometry']['location']['lat'] // same for ['lng'] 

你忘了把指數

$data['results'][0]['geometry']['location']['lat'] // same for ['lng'] 
0

你似乎已經錯過了$data['results']是有一個元素的數組,因此您需要使用[0]來引用該元素。

嘗試:$data['results'][0]['geometry']['location']['lat']