在JSON / API处理期间出现错误的错误

时间:2014-09-27 09:26:53

标签: php json api curl

我使用riots api(英雄联盟)来获取一些使用json / php / curl的信息。我偶然发现了一条我不明白的错误信息。此代码无效

$ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'https://euw.api.pvp.net/api/lol/euw/v2.5/league/by-summoner/31827832?api_key=key');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$response = curl_exec($ch);

    curl_close($ch);
    //var_dump($response);

$json = json_decode($response, true);

     foreach($json['entries'] as $entry){

         echo $entry['playerOrTeamName'] . ',' . $json['tier'] . ',' . $entry['division'] . ',' . $entry['leaguePoints'] . ',' . $entry['wins'] . "<br/>";
        }

这是数组中的var_dump:

{
"name":"Ezreal's Zealots",
"tier":"PLATINUM",
"queue":"RANKED_SOLO_5x5",
"entries": [{
    "playerOrTeamId":"34458086",
    "playerOrTeamName":"OverdrivZ",
    "division":"V",
    "league‌​Points":21,
    "wins":102,
    "isHotStreak":false,
    "isVeteran":false,
    "isFreshBlood":false‌​,
    "isInactive":false
}]

错误消息:Notice: Undefined index: entries in /hermes/bosoraweb130/b411/ipg.notsureifpossiblecom/index.php on line 23

Warning: Invalid argument supplied for foreach() in /hermes/bosoraweb130/b411/ipg.notsureifpossiblecom/index.php on line 23

我的代码中的第23行是:

foreach($json['entries'][0] as $entry){

但是当我使用不同的api请求时,这个完全相同的代码会起作用:

ini_set("display_errors", "1"); error_reporting(E_ALL);

    $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://euw.api.pvp.net/api/lol/euw/v2.5/league/challenger?type=RANKED_SOLO_5x5&api_key=key');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $response = curl_exec($ch);

        curl_close($ch);

    $json = json_decode($response, true);

        foreach($json['entries'] as $entry){

            echo $entry['playerOrTeamName'] . ',' . $json['tier'] . ',' . $entry['division'] . ',' . $entry['leaguePoints'] . ',' . $entry['wins'] . "<br/>";
            }

唯一的变化是api url请求,即challenger版本。为什么此代码适用于此api url请求而不适用于第一个请求。我想要执行的回声应该适用于数组中显示的条目。我不明白发生了什么,一定是非常简单的事情?请帮帮我。

1 个答案:

答案 0 :(得分:1)

这个阵列似乎还有两个级别,所以你实际上有:

Array (
  [31827832] => Array (
   [0] => Array (
     [name] => Ezreal\'s Zealots
     [tier] => PLATINUM
     [queue] => RANKED_SOLO_5x5
     [entries] => Array (
       [0] => Array (
       [playerOrTeamId] => 34458086
       [playerOrTeamName] => OverdrivZ
       [division] => V
       [leaguePoints] => 21
       [wins] => 102
       [isHotStreak] =>
       [isVeteran] =>
       [isFreshBlood] =>
       [isInactive] =>
    )

好的,所以似乎数组中的第一个条目实际上是整数索引,其中包含播放器的id,所以我猜有一个API调用来获取它,但在这种情况下使用它:

$json = array_pop($json);
foreach($json[0]['entries'] as $entry){
    ....
}