How can I iterate through a JSON file with PHP and access the second element of the file? [duplicate]

1 week ago 7
ARTICLE AD BOX

I have a JSON file with geo coordinates and some features like this:

{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "mapImage": "start", "city": "XXX", "hdColor": "#8c0303", "iconWind": "mbike", "place": "xxx", "progressive": "xxx", "step": "1", "icon": "start_icon", "mapPoint": "start", "routeColor": "#ff0000" }, "geometry": { "type": "Point", "coordinates": [10.64396439843723, 44.69265308192274] } }, { "type": "Feature", "properties": { "mapImage": "start", "city": "YYY", "hdColor": "#8c0303", "iconWind": "mbike", "place": "xxx", "progressive": "xxx", "step": "2", "icon": "start_icon", "mapPoint": "start", "routeColor": "#ff0000" }, "geometry": { "type": "Point", "coordinates": [10.64396439843723, 44.69265308192274] } } ] }

Obviously, this is only the first item but the file contains a lot of elements ('feature') like this.

I need to iterate through the files and I use this code:

$file = file_get_contents('file.json'); $path = json_decode($file); if (JSON_ERROR_NONE !== json_last_error()) { printf("%s", json_last_error_msg()); exit; } } foreach ($path->features as $routes) { $start = $routes->properties->city); finish = ??? //point to the city element in the next 'feature' }

Here too, obviously, I have only transcribed the part necessary to understand the problem.

In the PHP code, I need to point to the CITY element of the second 'feature', which in this case would be YYY. I need to do this without altering the foreach loop iteration because in the next step, I'll need to point again to the CITY element of the current 'feature' (which in the meantime will have become number 2, i.e., YYY) and the next one.

In practice, I should always obtain the current and next CITY elements for the entire duration of the 'features' in the file:

So, to make myself clearer:

I need the 1st-2nd, then the 2nd-3rd, then the 3rd-4th, then the 4th-5th, then the 5th-6th, and so on.

I am not able to find out a working syntax in PHP.

I try also with while iteration. That works fine in a simple array, but I can't figure it out.

Read Entire Article