非法的字符串偏移量'key' [英] Illegal string offset '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返回一维数组,并且$champion
是foreach ($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屋!