繁体   English   中英

Foreach PHP 循环问题

[英]Foreach PHP looping troubles

我在解码我的 json 时遇到问题,它似乎只能解码“几何-> 坐标”字段之一,例如只有一个多边形。 它与#LINE 5 有关系。 我怎样才能解决它会实际工作。

我已经通过这里的帮助构建了我现在得到的东西: How to extract and access data from JSON with PHP?

# LINE 5

foreach($polygon->features[0]->geometry->coordinates as $coordinates)

# FULL CODE

<?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);

foreach($polygon->features[0]->geometry->coordinates as $coordinates)
{
    print_r($coordinates);
    
}
?>

您只是通过执行$polygon->features[0]循环第一个(或第零个)项目。 相反,也循环遍历这些功能:

foreach($polygon->features as $feature){
    foreach($feature->geometry->coordinates as $coordinates)
    {
        print_r($coordinates);
    
    }   
}

演示: https : //3v4l.org/kk0uZ

<?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); foreach($polygon->features as $feature) { foreach($feature->geometry->coordinates as $coordinates) { print_r($coordinates); } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM