非法的字符串偏移量'key' [英] Illegal string offset 'key'

查看:339
本文介绍了非法的字符串偏移量'key'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

// 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'];
    }
}

但是此$ championKey变量返回"o",并在屏幕上提示3条警告:

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

警告:第41行的E:\ xampp \ htdocs \ riot \ index.php中的字符串偏移量'key'非法

我还尝试使用isset()验证条目,但似乎无法正常工作.

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

在这里可以找到$ championMastery:

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

推荐答案

由于API返回一维数组,并且$championforeach ($jsonChampion as $champion)中的字符串值,因此出现错误.可以解决以下问题:

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

顺便说一句, $jsonChampion是一维数组,因此您可以检索$championKey而无需编写如下的foreach循环:

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

这篇关于非法的字符串偏移量'key'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆