I need to loop through a local JSON file using PHP and am struggling to access the correct info. I need to retrieve the coordinates for each country and push these into a new array, with the country name as a key and the coordinates as values.
The JSON file looks like:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": { "name": "Bahamas", "iso_a2": "BS", "iso_a3": "BHS", "iso_n3": "044" },
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[-77.53466, 23.75975],
[-77.78, 23.71],
[-78.03405, 24.28615],
[-78.40848, 24.57564],
[-78.19087, 25.2103],
[-77.89, 25.17],
[-77.54, 24.34],
[-77.53466, 23.75975]
]
],
[
[
[-77.82, 26.58],
[-78.91, 26.42],
[-78.98, 26.79],
[-78.51, 26.87],
[-77.85, 26.84],
[-77.82, 26.58]
]
],
[
[
[-77, 26.59],
[-77.17255, 25.87918],
[-77.35641, 26.00735],
[-77.34, 26.53],
[-77.78802, 26.92516],
[-77.79, 27.04],
[-77, 26.59]
]
]
]
}
},
{
"type": "Feature",
I've got the file in PHP using file_get_contents and json_decode, and have tried a foreach loop in PHP to access each nested element, but hit a snag when looping through the json with multiple errors:
Warning: foreach() argument must be of type array|object, null given
Warning: Undefined variable $features
How could I access the coordinates, and add them to a new array?
EDIT:
code I'm using is:
features[0]->geometry->coordinates[0][0][0][0] as $coordinates)
{
echo $coordinates;
}
?>