非法字符串偏移'键'

时间:2017-04-18 05:41:41

标签: php json rest

我有这段代码:

// 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条警告:

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

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

在这里检索$ championMastery:

$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 个答案:

答案 0 :(得分:1)

您收到错误,因为API返回一维数组,而foreach ($jsonChampion as $champion)foreach ($jsonChampion as $champion) { if (isset($jsonChampion['key'])) { $championKey = $jsonChampion['key']; } } 中的字符串值。以下可以修复:

$jsonChampion

顺便说一句, $championKey是一维数组,因此您可以在不编写foreach循环的情况下检索if(is_array($jsonChampion) && isset($jsonChampion['key'])){ $championKey = $jsonChampion['key']; } ,如下所示:

[UIView setAnimationsEnabled:NO];
[_cancleOrConfirmButton setTitle:@"Cancel" forState:UIControlStateNormal];
[UIView setAnimationsEnabled:YES];