Question

I'm new to php and this has really stumped me - i'm trying to parse this json in order to get the value of match_id.

{
    "result": {
        "status": 1,
        "num_results": 1,
        "total_results": 500,
        "results_remaining": 499,
        "matches": [
            {
                "match_id": 649218382,
                "match_seq_num": 588750904,
                "start_time": 1399560988,
                "lobby_type": 0,
                "players": [
                    {
                        "account_id": 4294967295,
                        "player_slot": 0,
                        "hero_id": 69
                    }
                ]

            }
        ]

    }
}

So far I have:

$matchhistoryjson = file_get_contents($apimatchhistoryurl);
$decodedmatchhistory = json_decode($matchhistoryjson, true);
$matchid = $decodedmatchhistory->{'match_id'};

But I'm pretty sure that's not the right way to do it at all. All I need out of this JSON file is the match id.

Was it helpful?

Solution

You are getting an array back from json_decode() as you passed the second parameter with a value of true so you access it like any multi-dimensional array:

$matchhistoryjson = file_get_contents($apimatchhistoryurl);
$decodedmatchhistory = json_decode($matchhistoryjson, true);
echo $decodedmatchhistory['result']['matches'][0]['match_id'];

Demo

Naturally if you have multiple matches you wish to get the match ID for you can loop through $decodedmatchhistory['result']['matches'] and get them accordingly.

OTHER TIPS

This is your code:

$matchhistoryjson = file_get_contents($apimatchhistoryurl);
$decodedmatchhistory = json_decode($matchhistoryjson, true);
$matchid = $decodedmatchhistory->{'match_id'};

Two issues. First when you set true in a call to json_decode() that returns the results as an array:

When TRUE, returned objects will be converted into associative arrays.

So you would access the data as an array like this:

$matchid = $decodedmatchhistory['match_id'];

But your original syntax is incorrect even if you were accessing the data as an object:

$matchid = $decodedmatchhistory->{'match_id'};

If you set json_decode() to false or even left that parameter out completely, you could do this instead:

$decodedmatchhistory = json_decode($matchhistoryjson);
$matchid = $decodedmatchhistory->match_id;

So try both out & see what happens.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top