首页 > 解决方案 > 如何使用 php 从嵌套 json 访问特定数据?

问题描述

这是 JSON 文本-

{
  "kind": "youtube#commentThreadListResponse",
  "etag": "\"SJZWTG6xR0eGuCOh2bX6w3s4F94/CTTPi63Nf0uw0VTa1vFAqqL88k8\"",
  "pageInfo": {
  "totalResults": 2,
  "resultsPerPage": 20
  },

  "items": [
  {
    "kind": "youtube#commentThread",
    "etag": "\"SJZWTG6xR0eGuCOh2bX6w3s4F94/adPDtbu8m9cY9xkHacyKvWARfR8\"",
    "id": "Ugy2poa2UDXYm-kUKWh4AaABAg",
    "snippet": {
      "videoId": "kVUIh5cp3mY",
      "topLevelComment": {
        "kind": "youtube#comment",
        "etag": "\"SJZWTG6xR0eGuCOh2bX6w3s4F94/xgKA1zcXGWvsBnMxKuksawMPqy8\"",
        "id": "Ugy2poa2UDXYm-kUKWh4AaABAg",
        "snippet": {
          "authorDisplayName": "Thelma S. Brittain",
          "authorProfileImageUrl": "https://yt3.ggpht.com/a/",
          "authorChannelUrl": "http://www.youtube.com/channel/",
          "authorChannelId": {
            "value": "UC1W2wC96X4SjdAewhPi-mpg"
          },
          "videoId": "kVUIh5cp3mY",
          "textDisplay": "Hello thanks for the video.",
          "textOriginal": "Hello thanks for the video.",
          "canRate": true,
          "viewerRating": "none",
          "likeCount": 0,
          "publishedAt": "2019-06-28T17:48:18.000Z",
          "updatedAt": "2019-06-28T17:48:18.000Z"
        }
      },
      "canReply": true,
      "totalReplyCount": 0,
      "isPublic": true
    }
  }
 ]
}

我通过使用 youtube API 得到了这个 JSON 文本。我正在尝试回显“authorDisplayName”和“textOriginal”,但它不起作用。我尝试了很多方法。我无法弄清楚我的错误。我试过这么远,

$url = file_get_contents("https://www.something.com");
$arr = json_decode($url, true);
echo $arr['items']->['snippet'][0]->['topLevelComment']->['snippet']->['authorDisplayName'];
echo $arr['items']->['snippet']->['topLevelComment']->['snippet']->['textOriginal'];

有人可以帮我解决这个问题吗?谢谢。

标签: phpjsonparsing

解决方案


您正在混合数组和对象表示法

echo $arr['items']->['snippet']->['topLevelComment']->['snippet']->['textOriginal'];

因为您已将 JSON 转换为关联数组(第二个参数为 true)并调整了层次结构......

$arr = json_decode($url, true);
echo $arr['items'][0]['snippet']['topLevelComment']['snippet']['authorDisplayName'];
echo $arr['items'][0]['snippet']['topLevelComment']['snippet']['textOriginal'];

推荐阅读