PHP读取geoJSON文件无法提取国家名称、编码为单独数组如何解决?
PHP提取GeoJSON多字段独立数组问题解决
问题原因
你的循环逻辑存在赋值覆盖问题:每次循环都直接给$output["name"]赋值,新值会直接覆盖上一轮的结果,因此最终只能拿到最后一个国家的name值。
解决方法
首先初始化要提取的各字段为空白数组,循环时使用追加语法[]往对应数组中新增元素即可。如果需要提取多个字段,可以在单次循环中同时处理,避免重复遍历数据。
修正后代码
ini_set('display_errors', 'On'); error_reporting(E_ALL); $executionStartTime = microtime(true); // 读取JSON文件 $json = file_get_contents('countryBorders.geo.json'); // 解码JSON为数组 $json_data = json_decode($json, true); $countryBorders = $json_data["features"]; $output["countryBorders"] = $countryBorders; // 先初始化各个目标字段为空数组 $output['name'] = []; $output['iso_a2'] = []; $output['iso_a3'] = []; $output['border'] = []; // 遍历所有国家数据,往对应数组追加元素 foreach ($countryBorders as $country) { $properties = $country['properties']; $output['name'][] = $properties['name']; $output['iso_a2'][] = $properties['iso_a2']; $output['iso_a3'][] = $properties['iso_a3']; $output['border'][] = $country['geometry']['coordinates']; } header('Content-Type: application/json; charset=UTF-8'); echo json_encode($output);
额外说明
- 不需要返回全量国家边界数据的话,可以删除
$output["countryBorders"] = $countryBorders;这行,降低接口返回体积 - 如果需要动态指定提取的字段,可以先定义要提取的字段列表,再循环处理,减少重复代码
内容的提问来源于stack exchange,提问作者Coder_k
相关产品推荐
相关产品推荐

