【问题标题】:Foreach PHP looping troublesForeach PHP 循环问题
【发布时间】:2021-12-27 00:15:21
【问题描述】:

我在解码我的 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);
    
}
?>

【问题讨论】:

  • 您是遇到错误,还是仅获得一个值?如果它只是一个值,你确定有不止一组坐标吗?您需要检查您的 JSON 以确定您需要循环的内容。

标签: php json foreach


【解决方案1】:

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

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

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

【讨论】:

  • Crazy 实际上尝试了类似的东西,但我没有工作,一定有 som 错误谢谢!
【解决方案2】:
<?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);
  }
}

【讨论】:

    猜你喜欢
    • 2013-12-10
    • 2015-09-21
    • 1970-01-01
    • 2014-05-13
    • 2015-10-30
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多