Geonames api 循环并获取城市名称

Geonames api loop and get city name

$jsonfile = file_get_contents("http://api.geonames.org/searchJSON?username=ksuhiyp&country=pt&maxRows=1000&style=SHORT");
    $jsondata = json_encode($jsonfile);
    $cities = explode(',', $jsondata);
    foreach($cities as $key => $value){
        echo $value;
    }

如何只获取数组中包含的所有城市名称(例如...里斯本、波尔图、阿威罗...)?

这是数组的示例:

{"totalResultsCount":37305,"geonames":[{"lng":"-9.13333","geonameId":2267057,"countryCode":"PT","name":"Lisbon","toponymName":"Lisbon","lat":"38.71667","fcl":"P","fcode":"PPLC"},{"lng":"-8.61099","geonameId":2735943,"countryCode":"PT","name":"Porto","toponymName":"Porto","lat":"41.14961","fcl":"P","fcode":"PPLA"},{"lng":"-8.42005","geonameId":2742032,"countryCode":"PT","name":"Braga","toponymName":"Braga","lat":"41.55032","fcl":"P","fcode":"PPLA"},{"lng":"-8.8882","geonameId":2262963,"countryCode":"PT","name":"Setúbal","toponymName":"Setúbal","lat":"38.5244","fcl":"P","fcode":"PPLA"},{"lng":"-8.13057","geonameId":2264397,"countryCode":"PT","name":"Portugal","toponymName":"Portuguese Republic","lat":"39.6945","fcl":"A","fcode":"PCLI"},

对于初学者来说,这是一种非常难看的获取数据的方式,因为您正在对已经是 json 的 json 数据进行编码,然后只循环处理生成的损坏字符串的片段.

这将为您提供一个仅包含名称的结果数组:

$jsonfile = file_get_contents("http://api.geonames.org/searchJSON?username=ksuhiyp&country=pt&maxRows=1000&style=SHORT");
$geodat = json_decode($jsonfile,true);
$names = array();
foreach($geodat['geonames'] as $geoname) {
    $names[] = $geoname['name'];
}
print_r($names);

示例输出:

Array (
    [0] => Lisbon
    [1] => Porto
    [2] => Braga
    [3] => Setúbal
    [4] => Portugal
    [5] => Coimbra
    [6] => Funchal
    [7] => Amadora
    [8] => Queluz
    [9] => Lisbon metropolitan area
    ...