Reputation: 1749
I need to parse this JSON using PHP
[{
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.91138,
"lng": 7.671783
},
"name": "Corso Vinovo, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.909979,
"lng": 7.676234
},
"name": "Il Tempio del Pane, Corso Cesare Battisti, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.907805,
"lng": 7.674952
},
"name": "Banca Intesa, Via Ferdinando Salotto, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}]
to extract the coordinates in lat / lon.
What have I to use after
echo $wayPoints->?????
and how I create a for cicle to extract all the coordinates?
Any help will be appreciated!!Thank you!
Cesare
EDIT: a code sample (note that the JSON come from a POST parameter ...)
<?php
echo "Waypoints ...</br>";
echo "</br>";
echo $_POST['wayPoints'];
$wayPoints = $_POST['wayPoints'];
$json = json_decode($wayPoints);
foreach($json as $f){
echo $f['latLng']['lat'];
echo $f['latLng']['lng'];
}
?>
so should be more clear ... (the code NOT working ...)
Thank you again ...
EDIT 2: this code work !!!
<?php
echo "Waypoints ...</br>";
echo "</br>";
echo $_POST['wayPoints'];
$wayPoints = $_POST['wayPoints'];
$json = json_decode($wayPoints, true);
foreach($json as $f){
echo "</br>";
echo $f['latLng']['lat'];
echo "</br>";
echo $f['latLng']['lng'];
echo "</br>"; }
?>
the output is
44.91138
7.671783
44.909979
7.676234
44.907805
7.674952
Thank you all!
Upvotes: 0
Views: 150
Reputation: 141
This will convert your json object into an associative array, then iterate with foreach.
//use json_decode in associative mode
$decoded = json_decode($json, true);
//Your object is now an array called $decoded
//Your locations are subarrays of $decoded
//The co-ords are subarrays of each $locationArray
foreach($decoded as $locationArray)
{
echo "The co-ordinates for {$locationArray['name']} are: {$locationArray['latLng']['lat']},{$locationArray['latLng']['lng']}" . PHP_EOL;
}
Upvotes: 1
Reputation: 2180
First you need to do $file = json_decode()
and then the file you get just add to foreach:
foreach($file as $f){
echo $f['latLng']['lat'];
echo $f['latLng']['lng'];
}
Upvotes: 1