如何使用PHP从JSON代码获取数据?

时间:2014-07-12 16:45:33

标签: php json

数据来自from here

我想打印来自"playerStatSummaryType": "RankedSolo5x5"的胜利,那么如何从RankedSolo5x5获取数据?

这是我的代码:

$claw = "https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/43216818/summary?season=SEASON4&api_key=010ba2bc-2c40-4b98-873e-b1d148c9e379";
$z0r = file_get_contents($claw);
$gaza = json_decode($z0r, true);
$wins = $gaza['playerStatSummaries'][4]['wins'];
print $wins;

2 个答案:

答案 0 :(得分:1)

$wins = $gaza['playerStatSummaries'][4];
echo $key = array_search('RankedSolo5x5', $wins);

它将返回其类型名称

答案 1 :(得分:0)

以这种方式试试。由于JSON数据格式是奇数,因此滚动浏览返回的' playerStatSummaries'数组和作用于'PlayerStatSummaryType'等于' RankedSolo5x5'似乎是最好的面向未来的解决方案:

$claw = "https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/43216818/summary?season=SEASON4&api_key=010ba2bc-2c40-4b98-873e-b1d148c9e379";
$z0r = file_get_contents($claw);
$gaza = json_decode($z0r, true);

// Roll through the 'playerStatSummaries' array & act on the 'playerStatSummaryType' that equals 'RankedSolo5x5'.
$wins = '';
foreach ($gaza['playerStatSummaries'] as $key => $value) {
  if ($value['playerStatSummaryType'] == 'RankedSolo5x5') {
    $wins = $value['wins'];
  }
}

// Return the value of `$wins`.
echo $wins;

// Check the output of `$gaza` for debugging.
echo '<pre>';
print_r($gaza);
echo '</pre>';

我还添加了print_r($gaza);,以便您可以实际查看从呼叫返回的数据。可视化输出是调试此类过程的最佳方法。

数组的结构如下所示:

Array
(
    [summonerId] => 43216818
    [playerStatSummaries] => Array
        (
            [0] => Array
                (
                    [playerStatSummaryType] => AramUnranked5x5
                    [wins] => 41
                    [modifyDate] => 1405178930000
                    [aggregatedStats] => Array
                        (
                            [totalChampionKills] => 632
                            [totalTurretsKilled] => 26
                            [totalAssists] => 1491
                        )

                )

您希望采取行动的数据点是:

[5] => Array
    (
        [playerStatSummaryType] => RankedTeam3x3
        [wins] => 4
        [losses] => 1
        [modifyDate] => 1381833912000
        [aggregatedStats] => Array
            (
                [totalChampionKills] => 33
                [totalMinionKills] => 319
                [totalTurretsKilled] => 6
                [totalNeutralMinionsKilled] => 33
                [totalAssists] => 44
            )

    )