如何从API响应数组

时间:2015-08-02 22:43:29

标签: php api foreach

我正在尝试从已返回PHP数组的API响应中循环数据但是我在循环数据时遇到问题。

我正在使用Tumblr API,并想循环遍历数组返回的blog_names。

这是我到目前为止所尝试的内容:

API响应var_dump($info)

object(stdClass)[4]
  public 'meta' => 
    object(stdClass)[5]
      public 'status' => int 200
      public 'msg' => string 'OK' (length=2)
  public 'response' => 
    array (size=20)
      0 => 
        object(stdClass)[6]
          public 'blog_name' => string 'zolloc' (length=6)
          public 'id' => int 124153530139
          public 'post_url' => string 'http://zolloc.com/post/124153530139/david-hart-nyfwm-davidhartnyc-cfda-cadillac' (length=79)
          public 'slug' => string 'david-hart-nyfwm-davidhartnyc-cfda-cadillac' (length=43)
          public 'type' => string 'photo' (length=5)
          public 'date' => string '2015-07-15 13:34:10 GMT' (length=23)
          public 'timestamp' => int 1436967250
          public 'state' => string 'published' (length=9)
          public 'format' => string 'html' (length=4)
          public 'reblog_key' => string 'QhlVD4ex' (length=8)
          public 'tags' => 
            array (size=15)
              ...
          public 'short_url' => string 'http://tmblr.co/Zh19vx1pe88SR' (length=29)
          public 'recommended_source' => null
          public 'featured_in_tag' => 
            array (size=3)
              ...
          public 'featured_timestamp' => int 1437012340
          public 'highlighted' => 
            array (size=0)
              ...
          public 'note_count' => int 800
          public 'source_url' => string 'http://zolloc.com' (length=17)
          public 'source_title' => string 'zolloc.com' (length=10)
          public 'caption' => string 'david hart / nyfwm davidhartnyc cfda cadillac' (length=45)
          public 'reblog' => 
            object(stdClass)[7]
              ...
          public 'trail' => 
            array (size=1)
              ...
          public 'link_url' => string 'http://zolloc.com' (length=17)
          public 'image_permalink' => string 'http://zolloc.com/image/124153530139' (length=36)
          public 'photos' => 
            array (size=1)
              ...

尝试循环数据以获取每个blog_name

foreach($info['response'] as $item) {

    echo $item['blog_name'];
}

有人可以告诉我,为了访问阵列中的数据,我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

$ info 响应数组中存储的元素都是对象,因此您需要使用对象语法来访问日期。用以下代码替换你的循环:

foreach($info->response as $item) {
  echo $item->blog_name;
}