我有一個JSON從Google Maps API返回,我只想要檢索州/縣/地區和國家。如何搜索包含某些內容的數組中的值?
我用下面簡單的代碼通過PHP得到這個JSON:
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address=the+address&sensor=true&key=my+api+key';
// make the HTTP request
$data = @file_get_contents($url);
$jsondata = json_decode($data,true);
呼應$的數據給了我這樣的:
{
"results" : [
{
"address_components" : [
{
"long_name" : "9",
"short_name" : "9",
"types" : [ "street_number" ]
},
{
"long_name" : "Hanover Street",
"short_name" : "Hanover St",
"types" : [ "route" ]
},
{
"long_name" : "Edinburgh",
"short_name" : "Edinburgh",
"types" : [ "locality", "political" ]
},
{
"long_name" : "City of Edinburgh",
"short_name" : "City of Edinburgh",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Scotland",
"short_name" : "Scotland",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United Kingdom",
"short_name" : "GB",
"types" : [ "country", "political" ]
},
{
"long_name" : "EH2",
"short_name" : "EH2",
"types" : [ "postal_code_prefix", "postal_code" ]
},
{
"long_name" : "Edinburgh",
"short_name" : "Edinburgh",
"types" : [ "postal_town" ]
}
]
}
],
"status" : "OK"
}
什麼,我想訪問多維內array * address_components *,並且我認爲每次來自Google的JSON響應都會給我相同數量的數組,所以我一直使用簡單的數字索引來訪問我需要的數據。
即我認爲某些$jsondata['results'][0]['address_components'][4]['long_name']
總會給我'的行政_area_level_2'的long_name值 - 在這種情況下,'愛丁堡市',但我錯了。
有時會有更多的地址組件,有時甚至更少。這意味着我需要一種搜索這個數組的方法,然後獲取它的索引。
這是怎麼做的?如在中,我如何搜索哪個地址組件的類型爲'administrative_area_level_1',然後返回那個'long_name'值?