You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 00:06:03