0

我一直在尝试解析一个 json 数组,但没有成功。我可以得到一个根元素,但不能得到任何数组元素。下面是我的来自 Foursquare 的 json 数组的开头,它具有重复出现的场地元素。

     response: {
          keywords: {}
          suggestedRadius: 10000
          headerLocation: "here"
          headerFullLocation: "here"
          headerLocationGranularity: "unknown"
          headerMessage: "Suggestions for Friday evening"
          totalResults: 214
             groups: [
               {
                  type: "Recommended Places"
                  name: "recommended"
                  items: [
                      {
                       reasons: {
                       count: 0
                       items: [ ]
                        }
                       venue: {
                            id: "4b799a05f964a520b1042fe3"
                            name: "Green Gables"
                            contact: {
                            phone: "3097472496"
                            formattedPhone: "(309) 747-2496"
                                  }
                            location: {
                            address: "17485 East 2500 North Rd"

下面是我尝试获取餐厅名称的 PHP 代码。

   $obj = json_decode($uri, true);

   foreach($obj['response']['groups'] as $p)
   {
   if(isset($p['items']))
   {
     foreach($p['items'] as $p1)
 {
  if(isset($p1['venue']))
  {
//   echo varDumpToString($p1['venue']);  // this dump works ok and shows the elements
 foreach($p1['venue'] as $p2)
 {

     echo varDumpToString($p2['name']);   //  This is where I get the error
   }
   }
   }
   }   
   }

程序深入到 name 元素,然后给我一个错误,说“未定义的索引:名称”和“非法字符串偏移名称”。此消息出现 14 次,这是数组中每个项目的一次。那么为什么是“名称”无法识别?

4

2 回答 2

2

response.groups[x].items[y].venue is not an array. You are currently trying to access response.groups[x].items[y].venue[z].name, but you are actually accessing response.groups[x].items[y].venue.id.name, which does not exist. That last foreach iterates over the venue properties, not the venues. There is only one venue for each item.

This is what it should look like:

$obj = json_decode($uri, true);

foreach ($obj['response']['groups'] as $group) {
    if (isset($group['items'])) {
        foreach ($group['items'] as $item) {
            if (isset($item['venue'])) {
                echo varDumpToString($item['venue']['name']);
            }
        }
    }
}
于 2013-03-30T18:21:20.960 回答
0

Try changing this line,

 foreach($p1['venue'] as $p2)

to

 foreach($p1['venue'] as $p2Key => $p2)
于 2013-03-30T18:25:23.007 回答