Illegal string offset 'key'

2019-03-04 23:12发布

I have this code:

// Champion name and splash art
$endpointChampion = file_get_contents("https://global.api.riotgames.com/api/lol/static-data/BR/v1.2/champion/".$championMastery."?api_key=MYKEY");
$jsonChampion = json_decode($endpointChampion, true);

foreach ($jsonChampion as $champion) {  
    if (isset($jsonChampion['key'])) {
        $championKey = $champion['key'];
    }
}

But this $championKey variable returns "o" and 3 warnings are prompted on screen:

Warning: Illegal string offset 'key' in E:\xampp\htdocs\riot\index.php on line 41

I also tried to validate the entry, using isset() but seems not work properly.

The $championMastery is retrieved here:

$endpointMastery = file_get_contents("https://br.api.riotgames.com/championmastery/location/BR1/player/8083198/champions?api_key=MYKEY");
$jsonMastery = json_decode($endpointMastery, true);

foreach ($jsonMastery as $mastery) {
    $championMastery = $mastery['championId'];
    $masteryLevel = $mastery['championLevel'];
}

screenshot

标签: php json rest
1条回答
我想做一个坏孩纸
2楼-- · 2019-03-04 23:33

You are getting error because API returns one dimensional array and $champion is string value in foreach ($jsonChampion as $champion). Following can be fix:

foreach ($jsonChampion as $champion) {
      if (isset($jsonChampion['key'])) {
          $championKey = $jsonChampion['key'];
      }
}

BTW, $jsonChampion is one dimensional Array so you can retrieve $championKey without writing foreach loop as follows:

if(is_array($jsonChampion) && isset($jsonChampion['key'])){
      $championKey = $jsonChampion['key'];
}
查看更多
登录 后发表回答