2012-08-01 47 views
0

我的程序員無法從這個json數組中獲取location數據(經度和緯度)。什麼是foreach循環會發現location:緯度/經度並回顯它們?由於搜索這個json數組的有效方法?

$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" 
    }; 

回答

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"; 
} 
+0

由於我沒有那麼想通將需要一個循環來搜索整個陣列的程序員。 – Anagio 2012-08-01 19:28:31

+0

不是問題!如果返回多個結果,您將需要一個循環。我更新了我的答案,因爲我忘記了list()不能用於關聯數組。 – nickb 2012-08-01 19:31:23

+0

嗯..我很困惑。爲什麼在'結果'之後它的路徑爲零而不是這樣:$ jsonArray ['results'] ['geometry'] ['location'] ['lat']? 結果是一個數組,所以如果你說['results'] [0],你需要第一個元素是「address_components」。 您的代碼有效,但我只是不能理解零:) – mt0s 2012-11-03 00:21:28

相關問題