Home > Software engineering >  Foreach PHP looping troubles
Foreach PHP looping troubles

Time:11-16

I'm having trouble decoding my json it seems only to decode one of the "geometry->coordinates" fields like only one polygon. It has something with # LINE 5 to do. How can i fix it will actual work.

i've built what i got now with help from here: 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);
    
}
?>

CodePudding user response:

You are only looping over the first (or zeroth) item by doing $polygon->features[0]. Instead, loop over those features, too:

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

Demo: https://3v4l.org/kk0uZ

CodePudding user response:

<?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);
  }
}
  • Related