解析Twitch API响应PHP

时间:2019-06-10 01:13:58

标签: json parsing twitch-api

我正在尝试解析Twitch用户玩特定游戏的请求 。结果如下:

{
    "data":
    [{
        "id":"id here",
        "user_id":"uid here",
        "user_name":"name here",
        "game_id":"gameid here",
        "community_ids":[IDs here],
        "type":"live",
        "title":"awesome title here",
        "viewer_count":10,000,000,
        "started_at":"time here",
        "language":"en",
        "thumbnail_url":"url here",
        "tag_ids":[look at all these tags!]
    },{
        "id":"id here",
        "user_id":"uid here",
        "user_name":"name here",
        "game_id":"gameid here",
        "community_ids":[IDs here],
        "type":"live",
        "title":"awesome title here",
        "viewer_count":10,000,000,
        "started_at":"time here",
        "language":"en",
        "thumbnail_url":"url here",
        "tag_ids":[look at all these tags!]
        etc. etc.
    }],
    "pagination":{"cursor":"whatever this does"}
}

我正尝试通过以下方式对其进行解析:

$results = json_decode($query, TRUE);
foreach($results as $data){
    foreach($data as $users){
        echo ($users['user_name']."<br/>");
    }
}

我得到的结果如下:

name 1
...
name n

Warning: Illegal string offset 'user_name'
*first letter of pagination thing here (in this example it would be the 'w' in 'whatever')*

理想情况下,我希望返回:

user_Name, viewer_count, language,title

但是我停留在第一步...

1 个答案:

答案 0 :(得分:0)

您使用了太多的for循环。这应该起作用:

<?php
        foreach($results['data'] as $data){
            echo ($data['user_name']."<br/>");
        }