2010-07-08 43 views
1

我有以下代碼。我試圖從請求的提要中獲取城市的名稱,並將其轉換爲新的數組。任何人都可以給我一個指示。從json響應中獲取城市數組

$city = $_GET['city']; 
$json = @file_get_contents('http://ws.geonames.org/searchJSON?country=GB&maxRows=10&name_startsWith=$city'); 
$json = utf8_encode($json); 

$city_suggest = json_decode($json, true); 
foreach($city_suggest['geonames'] as $city){ 
    $cities = $city['geonames']['name'];  
} 
print_r ($cities); 

編輯 - 1線JSON響應

{"totalResultsCount":323,"geonames":[{"countryName":"United Kingdom","adminCode1":"ENG","fclName":"city, village,...","countryCode":"GB","lng":-0.12883186340332,"fcodeName":"capital of a political entity","toponymName":"London","fcl":"P","name":"London","fcode":"PPLC","geonameId":2643743,"lat":51.5005149421307,"adminName1":"England","population":7556900}, 

編輯的 - 的var_dump

array(2) { ["totalResultsCount"]=> int(0) ["geonames"]=> array(0) { } } 
+1

你應該告訴我們$ city_suggest – 2010-07-08 17:50:54

+0

是做什麼的(我相信你有問題;-))'var_dump(json_decod e($ json,true))' 可能是因爲file_get_contents使用單引號而不是雙引號。 – 2010-07-08 18:01:20

+0

你的json調用是錯誤的,你傳遞$ city作爲URL的一部分,而不是將它連接到最後。 – 2010-07-08 18:03:04

回答

2

你在你的foreach城市GEONAMES一部分是已經,所以你不需要有
$city['geonames']['name'],只是$city['name']

+0

這纔是真正的原因。事實證明,我花了10分鐘解決問題的其他原因之一是我不小心將一個流氓符號放入JSON URL中。它一切正常,但什麼也沒有返回。非常感謝。 – kalpaitch 2010-07-08 18:05:24

1

的響應請var_dump$city_suggest看到這個可變的結構。有了這些信息,提取您需要的數據應該相當容易。
不過,試試這個來代替:

$cities[] = $city->name; 
+0

只有當調用json_decode'是'json_decode($ json,false);' – artlung 2010-07-08 18:49:50

1
$cities = array(); 
foreach($city_suggest['geonames'] as $city){ 
    $cities[] = $city['name'];  
} 
+0

好點。謝謝 – kalpaitch 2010-07-08 18:03:53

1
$city = $_GET['city']; 
$json = file_get_contents("http://ws.geonames.org/searchJSON?country=GB&maxRows=10&name_startsWith=" . rawurlencode($city)); 
$json = utf8_encode($json); 
$city_suggest = json_decode($json, true); 
foreach($city_suggest['geonames'] as $city){ 
    print $city['name']; 
    // there are other available variables too 
    // print $city['countryName']; 
    // print $city['adminCode1']; 
    // print $city['fclName']; 
    // print $city['countryCode']; 
    // print $city['lng']; 
    // print $city['fcodeName']; 
    // print $city['toponymName']; 
    // print $city['fcl']; 
    // print $city['name']; 
    // print $city['fcode']; 
    // print $city['geonameId']; 
    // print $city['lat']; 
    // print $city['adminName1']; 
    // print $city['population']; 
} 

另外請注意,你有一句臺詞:

$json = @file_get_contents('http://ws.geonames.org/searchJSON?country=GB&maxRows=10&name_startsWith=$city'); 

$city不會被解釋,除非你用雙引號字符串,像這樣:

$json = @file_get_contents("http://ws.geonames.org/searchJSON?country=GB&maxRows=10&name_startsWith=$city");