PHP遍历嵌套JSON提取GeoJSON中各国坐标存入关联数组
错误原因
- 你调用
json_decode时第二个参数设为true,返回的是关联数组,不能用->对象运算符访问属性,必须使用[]数组语法 - 你写的遍历路径最终指向的是单个坐标数值(比如示例中的-77.53466),不是可遍历的数组,因此触发foreach参数类型错误
正确实现代码
目标生成以国家名为键、对应坐标为值的数组,代码如下:
<?php $geoJsonContents = file_get_contents("geoJsonInfo.json"); $geoJsonArray = json_decode($geoJsonContents, true); // 初始化目标存储数组 $countryCoordinates = []; // 遍历features层,每个元素对应一个国家的完整数据 foreach ($geoJsonArray['features'] as $feature) { // 提取国家名作为键 $countryName = $feature['properties']['name']; // 直接提取坐标数组作为对应值 $countryCoordinates[$countryName] = $feature['geometry']['coordinates']; } // 测试输出结果,正式使用可删除 var_dump($countryCoordinates); ?>
补充说明
如果需要提取所有单个坐标点做额外处理(比如去重、格式转换),可以使用多层遍历实现:
foreach ($geoJsonArray['features'] as $feature) { $countryName = $feature['properties']['name']; $pointList = []; // 遍历MultiPolygon下的所有多边形 foreach ($feature['geometry']['coordinates'] as $polygon) { // 遍历多边形的所有边界环 foreach ($polygon as $ring) { // 遍历边界的所有坐标点 foreach ($ring as $point) { // $point[0]为经度,$point[1]为纬度 $pointList[] = $point; } } } $countryCoordinates[$countryName] = $pointList; }
内容的提问来源于stack exchange,提问作者seemo127
相关产品推荐
相关产品推荐

