为了账号安全,请及时绑定邮箱和手机立即绑定

Geonames api 循环并获取城市名称

Geonames api 循环并获取城市名称

PHP
沧海一幻觉 2023-10-15 16:23:09
$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"},
查看完整描述

1 回答

?
慕的地8271018

TA贡献1796条经验 获得超4个赞

对于初学者来说,这是一种非常丑陋的获取数据的方式,因为您正在对已经是 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

    ...


查看完整回答
反对 回复 2023-10-15
  • 1 回答
  • 0 关注
  • 180 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信