在PHP中解析JSON以提取lat / lon

时间:2016-03-30 19:18:14

标签: php json parsing

我需要使用PHP解析这个JSON

[{
    "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
}]

提取lat / lon中的坐标。

后我要使用什么?
echo $wayPoints->?????

以及如何创建一个for cicle来提取所有坐标?

任何帮助将不胜感激!!谢谢!

切萨雷

编辑:代码示例(注意JSON来自POST参数......)

<?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'];
  }
?>

所以应该更清楚......(代码不工作......)

再次感谢你......

编辑2:这段代码工作!!!

<?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>";      }
?>

输出

44.91138
7.671783

44.909979
7.676234

44.907805
7.674952

谢谢大家!

2 个答案:

答案 0 :(得分:1)

首先你需要做$file = json_decode() 然后你得到的文件只是添加到foreach:

foreach($file as $f){
echo $f['latLng']['lat'];
echo $f['latLng']['lng'];
}

答案 1 :(得分:1)

这会将您的json对象转换为关联数组,然后使用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;
}