0

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);
    
}
?>
JonasW
  • 1
  • Are you getting an error, or just getting one value? If it's just one value, are you sure there are more than one set of coordinates? You'll need to inspect your JSON to figure out what you need to loop through. – aynber Nov 15 '21 at 20:17

2 Answers2

0

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

Chris Haas
  • 53,986
  • 12
  • 141
  • 274
  • Crazy actually tried something like that but i didn't work must had have som error thank you! – JonasW Nov 15 '21 at 20:21
0
<?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);
  }
}
Douma
  • 2,682
  • 14
  • 23