对于编程,我完全是新手,所以我甚至不确定我的条款是否正确,但是我想得到一些提示和提示,什么是最佳实践来循环JSON对象?假设我希望所有游戏名都来自于JSON的print_r输出。
stdClass Object
(
[_total] => 555
[_links] => stdClass Object
(
[self] => https://api.twitch.tv/kraken/games/top?limit=2&offset=0
[next] => https://api.twitch.tv/kraken/games/top?limit=2&offset=2
)
[top] => Array
(
[0] => stdClass Object
(
[viewers] => 86386
[channels] => 1159
[game] => stdClass Object
(
[name] => League of Legends
[_id] => 21779
[giantbomb_id] => 24024
[box] => stdClass Object
(
[template] => http://static-cdn.jtvnw.net/ttv-boxart/League%20of%20Legends-{width}x{height}.jpg
[small] => http://static-cdn.jtvnw.net/ttv-boxart/League%20of%20Legends-52x72.jpg
[medium] => http://static-cdn.jtvnw.net/ttv-boxart/League%20of%20Legends-136x190.jpg
[large] => http://static-cdn.jtvnw.net/ttv-boxart/League%20of%20Legends-272x380.jpg
)
[logo] => stdClass Object
(
[template] => http://static-cdn.jtvnw.net/ttv-logoart/League%20of%20Legends-{width}x{height}.jpg
[small] => http://static-cdn.jtvnw.net/ttv-logoart/League%20of%20Legends-60x36.jpg
[medium] => http://static-cdn.jtvnw.net/ttv-logoart/League%20of%20Legends-120x72.jpg
[large] => http://static-cdn.jtvnw.net/ttv-logoart/League%20of%20Legends-240x144.jpg
)
[_links] => stdClass Object
(
)
)
)
[1] => stdClass Object
(
[viewers] => 17288
[channels] => 162
[game] => stdClass Object
(
[name] => Hearthstone: Heroes of Warcraft
[_id] => 138585
[giantbomb_id] => 42033
[box] => stdClass Object
(
[template] => http://static-cdn.jtvnw.net/ttv-boxart/Hearthstone%3A%20Heroes%20of%20Warcraft-{width}x{height}.jpg
[small] => http://static-cdn.jtvnw.net/ttv-boxart/Hearthstone%3A%20Heroes%20of%20Warcraft-52x72.jpg
[medium] => http://static-cdn.jtvnw.net/ttv-boxart/Hearthstone%3A%20Heroes%20of%20Warcraft-136x190.jpg
[large] => http://static-cdn.jtvnw.net/ttv-boxart/Hearthstone%3A%20Heroes%20of%20Warcraft-272x380.jpg
)
[logo] => stdClass Object
(
[template] => http://static-cdn.jtvnw.net/ttv-logoart/Hearthstone%3A%20Heroes%20of%20Warcraft-{width}x{height}.jpg
[small] => http://static-cdn.jtvnw.net/ttv-logoart/Hearthstone%3A%20Heroes%20of%20Warcraft-60x36.jpg
[medium] => http://static-cdn.jtvnw.net/ttv-logoart/Hearthstone%3A%20Heroes%20of%20Warcraft-120x72.jpg
[large] => http://static-cdn.jtvnw.net/ttv-logoart/Hearthstone%3A%20Heroes%20of%20Warcraft-240x144.jpg
)
[_links] => stdClass Object
(
)
)
)
)
)我可以访问单行(不确定这是否是最佳实践):
$OBJ->method()->top[0]->game->name;但我不知道怎么循环所有的游戏名称。
任何帮助都非常感谢!
发布于 2014-03-18 16:52:02
创建一个空数组,循环对象顶部数组并填充空数组:
$allgames=array();
foreach($OBJ->method()->top as $ob){
$allgames[] = $ob->game->name;
}发布于 2014-03-18 16:51:55
“名称”是使用$OBJ->top[0]->game->name等访问的.因此,只需将foreach放在"top“数组上:
foreach($OBJ->top as $object) {
echo $object->game->name;
}发布于 2014-03-18 16:52:41
将JSON字符串加载到PHP中时,可以使用:
json_decode($string_of_json, true);true标志将加载到一个数组中,例如,可以使用foreach循环。
https://stackoverflow.com/questions/22485795
复制相似问题