【问题标题】:How to access data from API response array如何从 API 响应数组访问数据
【发布时间】:2015-08-02 22:43:29
【问题描述】:

我正在尝试从返回 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'];
}

谁能告诉我为了访问数组中的数据我错过了什么?

【问题讨论】:

标签: php api foreach


【解决方案1】:

$inforesponse数组中存储的元素都是objects,所以需要使用object语法来访问日期。将循环替换为:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多