php - 如何使用 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'];
有人可以帮我解决这个问题吗?谢谢。
解决方案
您正在混合数组和对象表示法
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'];
推荐阅读
- python - 如何在 PyCharm 中取回调试控制台?
- node.js - 猫鼬 find().populate()
- javascript - 找不到反应js模块:无法解析“文件保护程序”
- python - Python json.load() 按原样读取 \u003d
- python - 尝试从列表中替换多个匹配项时如何摆脱“字符串索引超出范围”错误?
- flutter - Flutter:带有 BottomBar 菜单的导航架构
- flutter - 扑。在 null 上调用了 getter ''。接收方:null 尝试调用:产品
- api - 在 IntelliJ 中单击 Run/Debug 时创建 Serenity 的 index.html
- c# - 获取列表类型