douchun3680 2013-09-09 08:48
浏览 23
已采纳

为什么我不能在PHP中访问此数组的第二级?

Recently, with help from the Stack Oveflow community, I learned how to work with JSON data that I got from the Google API. So, I thought I had a grasp on how to do roughly the same kind of action with JSON data from Blogger, again using the Google API.

However, it's been driving me crazy. I can't seem to get a handle on how to get at the right level of the array that I need.

What I am trying to do is get a selection of blog posts and then cherry pick out information and display it. Should be straight forward.

Right now my blog has only three test entries. I want to see if I can loop through the array I create from the JSON to display data. If I use this code:

$recentBlog = json_decode(file_get_contents("https://www.googleapis.com/blogger/v3/blogs/xxxxxxxxxxxxxxxxxxxx/posts?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx", true));

foreach ($recentBlog as $item)
{
    var_dump($item[0]);
}

... then I get data the first item only from the array. This makes sense to me. I looped through the array, but on each call, I only asked for the first item at the 0 position.

So I thought I would do this:

$recentBlog = json_decode(file_get_contents("https://www.googleapis.com/blogger/v3/blogs/xxxxxxxxxxxxxxxxxxxx/posts?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx", true));

$count = 0;
foreach ($recentBlog as $item)
{
    var_dump($item[$count]);
    $count = $count + 1;
}

... but I get the second and third item only. I do not get the first item anymore.

What is wrong with my code?

If it helps, this is Google's documentation about the format of the JSON that I get back.

  • 写回答

2条回答 默认 最新

  • douyan8070 2013-09-09 09:08
    关注

    You probably have a wrong parenthesis in your JSON decoding call:

    $recentBlog = json_decode(file_get_contents("https://[...]"), true);
    

    Note that I moved one parenthesis directly behind the file_get_contents() function. This way json_decode() will return you an iterable array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看