【问题标题】:Parse a decoded json array in PHP在 PHP 中解析解码的 json 数组
【发布时间】:2016-09-27 07:35:37
【问题描述】:

我有一个从 facebook API 收到的解码 json 数组:

$Myposts = json_decode($response->getBody());

当我打印 $Myposts 时:

var_dump($Myposts);

它给出了这个:

    object(stdClass)[16]
  public 'data' => 
    array (size=24)
      0 => 
        object(stdClass)[12]
          public 'message' => string 'a mesagge..' (length=65)
          public 'created_time' => string '2016-09-18T16:41:10+0000' (length=24)
          public 'id' => string '111110037' (length=35)
      1 => 
        object(stdClass)[28]
          public 'message' => string 'How brave !' (length=11)
          public 'story' => string 'XXX shared Le XX video.' (length=59)
          public 'created_time' => string '2016-09-18T13:37:33+0000' (length=24)
          public 'id' => string '102172976' (length=35)

      23 => 
        object(stdClass)[50]
          public 'message' => string '...a message..' (length=259)
          public 'story' => string 'Bi added 3 new photos.' (length=33)
          public 'created_time' => string '2015-12-11T20:54:21+0000' (length=24)
          public 'id' => string '102191588' (length=35)
  public 'paging' => 
    object(stdClass)[51]
      public 'previous' => string 'https://graph.facebook.com/v2.7/XXXX&__paging_token=YYYY&__previous=1' (length=372)
      public 'next' => string 'https://graph.facebook.com/v2.7/XXX/feed?access_token=DDDD&limit=25&until=XXX&__paging_token=XXXX' (length=362)

我是php新手,不知道如何处理这个输出,我想遍历所有消息并输出每条消息的created_time。

有什么想法吗?

编辑:我试过:echo $myPosts['data'][message]; 来自Parsing JSON file with PHP,但我有:“未定义的索引:消息”。这就是为什么我发布了一个新问题。

【问题讨论】:

  • 如果你想使用这些值而不是使用循环。
  • 我尝试使用循环,但我没有弄清楚如何提取数据数组。我用了这个:foreach ($aposts['data'] as $item) { echo "items:". $item['message'] ."\n"; },但出错了。

标签: php arrays json facebook-php-sdk


【解决方案1】:

json_decode的第二个参数将结果变成关联数组:

$myPosts = json_decode($response->getBody(), true);

foreach ($myPosts['data'] as $post) {
    var_dump($post['message']);
}

不使用第二个参数解码返回对象:

$myPosts = json_decode($response->getBody());

foreach ($myPosts->data as $post) {
    var_dump($post->message);
}

【讨论】:

  • 我测试了第一个,它有效!但我不知道为什么会出现这个错误:Notice: Undefined index: message in C:\wamp64\www\ctest.php on line 131 第二个,我得到了这个:Notice: Undefined property: stdClass::$message in C:\wamp64\www\ctest.php on line 138
  • 也许不是所有的帖子都有消息..你应该在显示之前检查帖子是否有消息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-23
  • 1970-01-01
  • 1970-01-01
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多