【问题标题】:Parsing JSON in PHP to extract lat/lon在 PHP 中解析 JSON 以提取纬度/经度
【发布时间】:2016-03-30 19:18:13
【问题描述】:

我需要使用 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
}]

提取纬度/经度坐标。

之后我有什么用

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

谢谢大家!

【问题讨论】:

    标签: php json parsing


    【解决方案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;
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 请注意,此答案仅在您将true 作为json_decode 的第二个参数传递时才有效
      • 谢谢 Marko ...我已经尝试在我的原始请求中添加一个小代码示例 ....我已经尝试了您的建议,但它不起作用... :-)
      • @Cesare 是的,我忘了在json_decode 中提到true 参数
      猜你喜欢
      • 2010-11-21
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 2020-06-28
      • 2017-04-06
      • 2013-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多