以下信息保存在$ data中,我想在一行中获取“获胜次数”的值,在下一行中获取“等级”?如何实现不使用类似于前两行的语法:
// $tier =$data->{20720131}->tier
// $wins = $data->{20720131}[0]->entries[wins]
$data = json_decode(file_get_contents(###));
returns this when i echo it
{"20720131": [{
"queue": "RANKED_SOLO_5x5",
"name": "Taric`s Zealots",
"entries": [{
"leaguePoints": 0,
"isFreshBlood": false,
"isHotStreak": false,
"division": "V",
"isInactive": false,
"isVeteran": false,
"playerOrTeamName": "MikeDog",
"playerOrTeamId": "20720131",
"wins": 4
}],
"tier": "SILVER"
}]}';
答案 0 :(得分:2)
我假设您不希望这样做,因为您不确定该号码将永远是什么。
所以,你可以这样做。
$data = '{"20720131": [{
"queue": "RANKED_SOLO_5x5",
"name": "Taric`s Zealots",
"entries": [{
"leaguePoints": 0,
"isFreshBlood": false,
"isHotStreak": false,
"division": "V",
"isInactive": false,
"isVeteran": false,
"playerOrTeamName": "MikeDog",
"playerOrTeamId": "20720131",
"wins": 4
}],
"tier": "SILVER"
}]}';
$data = (array) json_decode($data);
$data = current(current($data));
var_dump($data->tier);
答案 1 :(得分:2)
自PHP 5.4起,您可以这样做:
$wins = json_decode($data, true)['20720131'][0]['tier'];
$tier = json_decode($data, true)['20720131'][0]['entries'][0]['wins'];
根据您的要求,只需2行。
更好的方式,更兼容,将是:
$data_array = json_decode($data, true);
$wins = $data_array['20720131'][0]['tier'];
$tier = $data_array['20720131'][0]['entries'][0]['wins'];
但那是3行。
答案 2 :(得分:0)
也可以使用正则表达式完成。我不推荐。
preg_match_all("/wins\": ([0-9]*)\n.*\n.*tier\": \"([A-Z]*)/i", $data, $output);
$wins = $output[1];
$tier = $output[2];