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

PHP使用foreach遍历GeoJSON仅能获取单个Polygon坐标如何修复

问题根因

你当前代码仅能获取单个Polygon坐标的核心问题是foreach遍历范围写死了features[0],仅读取了features数组的第一个元素,没有覆盖所有Feature;同时GeoJSON的Polygon类型coordinates为三层嵌套结构,直接遍历外层仅能拿到多边形环数组,无法直接获取坐标点。

修改后的完整代码

<?php
$str = '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[9.78281,54.923985],[9.80341,54.901586],[9.819803,54.901981],[9.83551,54.908396],[9.825897,54.91481],[9.822721,54.927142],[9.807186,54.927931],[9.792767,54.926797],[9.78281,54.923985]]]},{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[9.914474,54.930298],[9.901085,54.912343],[9.849243,54.912146],[9.846497,54.928917],[9.890785,54.946865],[9.930267,54.937399],[9.914474,54.930298]]]}}]}';

$polygon = json_decode($str);

// 遍历所有Feature对象
foreach($polygon->features as $singleFeature) {
    // 遍历当前Polygon的外环坐标点
    foreach($singleFeature->geometry->coordinates[0] as $coordinate) {
        print_r($coordinate);
    }
}
?>

可选适配方案

如果你的数据中存在带内环(空心)的Polygon,可调整坐标遍历逻辑,覆盖所有环的坐标:

foreach($polygon->features as $singleFeature) {
    // 遍历当前Polygon的所有环(外环+所有内环)
    foreach($singleFeature->geometry->coordinates as $ring) {
        // 遍历单个环的所有坐标点
        foreach($ring as $coordinate) {
            print_r($coordinate);
        }
    }
}

内容的提问来源于stack exchange,提问作者JonasW

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:36:05