donglu8334 2017-04-18 05:41
浏览 39
已采纳

非法字符串偏移'键'

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\htdocsiot\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

  • 写回答

1条回答 默认 最新

  • dsf12123 2017-04-18 05:51
    关注

    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'];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分