使用PHP从JSON Array获取数据

时间:2017-03-11 08:09:23

标签: php arrays

当我运行API请求时,我会收到以下数据。

如何使用PHP从中获取subscriberCount数据?

{
 "kind": "youtube#channelListResponse",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "statistics": {
    "subscriberCount": "80021",
   }
  }
 ]
}

我试过这个,但没有成功:

<?php

$json = '{
 "kind": "youtube#channelListResponse",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "statistics": {
    "subscriberCount": "80021",
   }
  }
 ]
}';

$yummy = json_decode($json);

echo $yummy->subscriberCount;

?>

1 个答案:

答案 0 :(得分:2)

我发现您需要移除,附近的80021

{
 "kind": "youtube#channelListResponse",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "statistics": {
    "subscriberCount": "80021"
   }
  }
 ]
}

您可以尝试使用此代码:

$yummy = json_decode($json);

echo $yummy->items[0]->statistics->subscriberCount;

然后你的结果就可以了。