dongyu6276 2014-10-19 20:01 采纳率: 0%
浏览 37
已采纳

JSON使用PHP将数据提取到变量中

I'm using a YouTube data API request to grab the channel id, but i'm not too sure why it isn't working:

The returned JSON request i'm getting is:

{
     "kind": "youtube#channelListResponse",
     "etag": "\"PSjn-HSKiX6orvNhGZvglLI2lvk/k5qSWj-xcF96jAN3p1uQH1amSRc\"",
     "pageInfo": {
      "totalResults": 1,
      "resultsPerPage": 5
     },
     "items": [
      {
       "kind": "youtube#channel",
       "etag": "\"PSjn-HSKiX6orvNhGZvglLI2lvk/e1xTbLf6JLhwwzeWbdMfWdPfcwg\"",
       "id": "UC-lHJZR3Gqxm24_Vd_AJ5Yw"
      }
     ]
    }

To extract the JSON data i'm using the a few lines of code and a function in php:

$banner_data = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=brandingSettings&forUsername=pewdiepie&key=AIzaSyDTxvTLWXStUrhzgCDptVUG4dGBCpyL9MY');
$banner_data = json_decode($banner_data, true);
$YTid = $banner_data['items']['id'];

When i :

echo "YouTube Channel Id Of pewdiepie is " . $YTid . ".<br />";

I don't get the channel id? What's my problem?

  • 写回答

2条回答 默认 最新

  • douzi8127 2014-10-19 20:04
    关注

    Items is an array containing one or more objects. So it has to be:

     $YTid = $banner_data['items'][0]->id;
    

    This way you grab 'id' from the first item in the items-array.

    BTW: learning to debug is crucial to learning to code. If you decode the json and then print the outcome you can see the structure of the array, which could have helped you to find the problem, like:

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

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?