如何从此JSON数组中获取变量值?

时间:2017-12-24 20:25:35

标签: php json

所以我有一个返回以下内容的URL:

[{"_id":{"champ2_id":63,"champ1_id":2,"role":"TOP"},"count":4,"champ1":{"thirtyToEnd":0,"goldEarned":10727.5,"zeroToTen":0,"minionsKilled":158,"winrate":0,"assists":6.25,"role":"TOP","deaths":6,"kills":4,"wins":0,"totalDamageDealtToChampions":17350.75,"twentyToThirty":0,"tenToTwenty":0,"neutralMinionsKilledTeamJungle":1.75,"killingSprees":0.75,"weighedScore":27214.5375},"champ2":{"twentyToThirty":0,"wins":4,"winrate":1,"kills":5.75,"neutralMinionsKilledTeamJungle":5,"totalDamageDealtToChampions":21881.25,"role":"TOP","assists":7,"tenToTwenty":0,"thirtyToEnd":0,"zeroToTen":0,"goldEarned":12371.75,"killingSprees":1.25,"minionsKilled":140.5,"deaths":4.25,"weighedScore":33166.587499999994}]

我已经学会了在URL返回更简单的东西时如何获取数组中键的值。例如,如果URL返回:

{"id":34743514,"accountId":49161997,"name":"League of Fiddle","profileIconId":786,"revisionDate":1514093712000,"summonerLevel":52}

我可以用这段代码回复id:

$json = file_get_contents(URL);
$data = json_decode($json, true);
echo $data['id'];

这很容易。但是当我尝试使用相同的代码来处理更复杂的东西时,比如说我想获得_id champ2_id的值,我已经尝试过:

$json = file_get_contents(URL);
$data = json_decode($json, true);
echo $data['_id']['champ2_id'];

但是这表示_id是一个未定义的索引。我做错了什么?

1 个答案:

答案 0 :(得分:3)

应该是

$data[0]['_id']['champ2_id'];