如何以选定的id显示JSON中的特定数据

时间:2016-11-12 16:39:56

标签: php json

我想问你怎么格式化我输出的地方" id"是142和stats文本是:totalSessionsWon。

来自以下JSON的PHP:

{
"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
        }
    }

我是php和json的初学者,我似乎无法在这个问题上找到答案,也许是因为我不知道如何正确地提出这个问题。

1 个答案:

答案 0 :(得分:2)

首先,这是 NOT 有效的JSON,所以我猜测你已经从没有实现的任何来源复制和粘贴,所以这已经针对下面的例子进行了修复。

$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'];

见:

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

修改

$value['id']更改为142,因为它是143