检索json数组中的对象


Retrieve objects inside json array

我正在尝试检索team1的分数,但我似乎不知道如何输出。到目前为止,我已经在$obj是json输出的情况下实现了这一点。

$obj->recent

JSON-

"recent": [
    [
        {
        "match_id": "64886",
        "has_vods": false,
        "game": "dota2",
        "team 1": {
            "score": "",
            "name": "Wheel Whreck While Whistling",
            "bet": "7%"
        },
        "team 2": {
            "score": "",
            "name": "Evil Geniuses DotA2",
            "bet": "68%"
        },
        "live in": "1m 42s",
        "title": "Wheel Whreck... 7% vs 68% Evil...",
        "url": "",
        "tounament": "",
        "simple_title": "Wheel Whreck... vs Evil...",
        "streams": []
        }
]

您需要使用json_decode();此函数返回包含数组和对象的正确对象。现在您需要检查什么是对象,什么是数组。

$obj = json_decode($obj, true);
$obj->recent; //array 
$obj->recent[0]; //first element of array
$obj->recent[0][0]; //first element of second array
$obj->recent[0][0]->{'team 1'}; //access to object team 1
$obj->recent[0][0]->{'team 1'}->score; //access to property of object team 1

你可以发现这有助于了解发生了什么;

您也可以查看json_decode文档上的示例

如果在$obj上使用var_dump函数,它将显示什么是数组,什么是对象。

您需要使用json_decode将其放入数组中。看起来recent是一个对象数组的数组。所以,你会做一些类似的事情

$json = json_decode($obj->recent, true);
$team1 = $json[0][0]['team 1']; //should return array
$score = $team1['score']

edit:感谢您的评论,缺少true作为json_decode 中的第二个参数