TonzZzy TonzZzy - 23 days ago 4
JSON Question

How to display specific data in JSON in selected id

i want to ask you how could i format to give me output where "id" is 142 and stats where text is: totalSessionsWon.

in PHP from the JSON below:

{
"summonerId":55595291,
"modifyDate":1477143625000,
"champions":[
{
"id":143,
"stats":{
"totalSessionsPlayed":1,
"totalSessionsLost":1,
"totalSessionsWon":0,
"totalChampionKills":1,
"totalDamageDealt":29811,
"totalDamageTaken":5853,
"mostChampionKillsPerSession":1,
"maxNumDeaths":5
}
},
{
"id":142,
"stats":{
"totalSessionsPlayed":1,
"totalSessionsLost":1,
"totalSessionsWon":0,
"totalChampionKills":0,
"totalDamageDealt":42796,
"totalDamageTaken":11616,
"mostChampionKillsPerSession":0,
"maxNumDeaths":6
}
}


I am beginner in php and json and i really cant seem to find answer on this question, maybe because i dont know how to ask the question properly.

Answer

Firstly, this was NOT valid JSON so I'm guessing you've copied and pasted from whatever source not realising so this has been fixed for the example below.

$json = '{
    "summonerId": 55595291,
    "modifyDate": 1477143625000,
    "champions": [{
        "id": 143,
        "stats": {
            "totalSessionsPlayed": 1,
            "totalSessionsLost": 1,
            "totalSessionsWon": 0,
            "totalChampionKills": 1,
            "totalDamageDealt": 29811,
            "totalDamageTaken": 5853,
            "mostChampionKillsPerSession": 1,
            "maxNumDeaths": 5
        }
    }, {
        "id": 142,
        "stats": {
            "totalSessionsPlayed": 1,
            "totalSessionsLost": 1,
            "totalSessionsWon": 0,
            "totalChampionKills": 0,
            "totalDamageDealt": 42796,
            "totalDamageTaken": 11616,
            "mostChampionKillsPerSession": 0,
            "maxNumDeaths": 6
        }
    }]
}';

//Decode JSON and set true for Associative Array for comparison Note yours failed to decode

$array = json_decode($json, true);

 //Use a foreach loop and if statement to pass the data you need into another array

 foreach ($array['champions'] as $value) {

     if ($value['id'] == 142) {

         $statsArray = $value['stats'];

     }

 }


//Show your friends how many sessions you have won
echo $statsArray['totalSessionsWon'];

See:

http://php.net/manual/en/function.json-decode.php

Edit

Changed $value['id'] to 142 as it was 143

Comments