使用PHP foreach循环解析数据json数据


parse the data json data using php foreach loop

我很麻烦从下面的json数据中提取数据,如lat lng等使用php foreach循环。

   {
    "deals": [
      "division": {
      "timezone": "Central Time (US & Canada)",
      "lat": 32.4487,
      "timezoneOffsetInSeconds": -18000,
      "id": "abilene",
      "lng": -99.7331,
      "timezoneIdentifier": "America/Chicago",
      "name": "Abilene, TX"
     },

我想解析的数据为晚lng等。这是我的PHP代码

      $json = file_get_contents($url);
      $json_string1 = json_decode($json);
      foreach($json_string1->deals as $mydata)
  {
      foreach($mydata->division as $p)
      {
      echo $p->lat;
      }
     }  

给出错误Trying to get property of non-object

这里有一个更好的答案,使用假定的JSON结构。如果你的JSON不是这样的,请编辑你的问题,然后先通过jsonlint或类似的程序运行你的JSON。

<?php
$json = <<<JSON
{
    "deals": [
        {
            "division": {
                "timezone": "Central Time (US & Canada)",
                "lat": 32.4487,
                "timezoneOffsetInSeconds": -18000,
                "id": "abilene",
                "lng": -99.7331,
                "timezoneIdentifier": "America/Chicago",
                "name": "Abilene, TX"
            }
        }
    ]
}
JSON;
  $json_string1 = json_decode($json, false);
  foreach($json_string1->deals as $mydata)
  {
    echo $mydata->division->lat;
  }
?>

在foreach循环中使用$json_string1变量代替$json_string变量