Trying to parse JSON with PHP

后端 未结 2 2013
情话喂你
情话喂你 2021-01-25 20:40

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\": {
        \         


        
2条回答
  •  长发绾君心
    2021-01-25 21:07

    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.

提交回复
热议问题