使用PHP循环嵌套JSON

时间:2016-01-08 23:40:35

标签: php json

我有像这样的json结构

[
  {
    “id” : 1,
    “user_id” : 1,
    “location” :  {
       “long” : 34.2489234,
       “lat” : -117.234234,
    },
    “active” : 1
  },   {
    “id” : 2,
    “user_id” : 2,
    “location” :  {
       “long” : 34.245234234,
       “lat” : -116.23786834,
    },
    “active” : 1
  },   {
    “id” : 3,
    “user_id” : 3,
    “location” :  {
       “long” : 34.245634234,
       “lat” : -114.237787834,
    },
    “active” : 0
   }
]

我怎样才能遍历数据,所以我只能获得“long”和“lat”的位置?

2 个答案:

答案 0 :(得分:1)

首先解码json-string:

$data = json_decode($the_json_string);

这将为您提供一个包含对象的php数组,您可以像往常一样循环访问:

foreach($data as $obj) {
    echo $obj->location->long;
    echo $obj->location->lat;
}

答案 1 :(得分:0)

  $data = json_decode($json,true);

    foreach ($data as $obj ){
      echo $obj['location']['long'];


      echo $obj ['locaion']['len'];
}

我希望这会起作用