本文介绍了在多维数组上运行一个php foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在多维数组上运行一个foreach脚本。
原始的JSON格式如下:
{
$ p $运行
_links:{
},
chatter_count:15,
chatters:{
moderators:[
moderator1 ,
moderator2,
moderator3
],
staff:[
staff1,
staff2,
staff3
],
admins:[
admin1,
admin2,
admin3
],
global_mods:[
global_mod1,
global_mod2,
global_mod3
],
查看者:[
viewer1,
viewer2,
viewer3
]
}
}
json_decode
得到一个PHP数据结构,我现在已经失去了如何运行一个foreach循环来输出像这样:
chatter_count:15
版主:
版主1
版主2
版主3
职员:
职员1
职员2
职员3
管理员:
admin1
admin2
admin3
global_mods:
global_mod1
global_mod2
global_mod3
$ b查看者:
viewer1
viewer2
viewer3
解决方案首先将json解码为数组,然后利用
$ key
打印数组:
<?php
$ testobj = json_decode(file_get_contents('https://tmi.twitch.tv/group/user/sodapoppin/chatters'),true);
echochatter_count:。$ testobj ['chatter_count']。\\\
;
$ b foreach($ testobj ['chatters'] as $ key => $ chatter){
echo\\\
$ key:\\\
;
foreach($ chatter as $ value){
echo$ value\\\
;
输出: p>
我从你给的URL得到这样的东西:
chatter_count: 5461
版主:
emilydk
fyzicul
hnl
hnlbot
ngmack
nixi93
psychostatik
sodapoppin
staystrong420
sxyhxy
美味的电话
$ b $员工:
evoli
pluto
...
...
...
I need to run a foreach script on a multi-dimensional array.
The original JSON is formatted like:
{ "_links":{ }, "chatter_count":15, "chatters":{ "moderators":[ "moderator1", "moderator2", "moderator3" ], "staff":[ "staff1", "staff2", "staff3" ], "admins":[ "admin1", "admin2", "admin3" ], "global_mods":[ "global_mod1", "global_mod2", "global_mod3" ], "viewers":[ "viewer1", "viewer2", "viewer3" ] } }
Having run
json_decode
to get a PHP data structure, I'm now lost on how to run a foreach loop to output something like:chatter_count: 15 moderators: moderator1 moderator2 moderator3 staff: staff1 staff2 staff3 admins: admin1 admin2 admin3 global_mods: global_mod1 global_mod2 global_mod3 viewers: viewer1 viewer2 viewer3
解决方案First decode the json to array, then make use of
$key
to print the array:<?php $testobj = json_decode(file_get_contents('https://tmi.twitch.tv/group/user/sodapoppin/chatters'), true); echo "chatter_count:".$testobj['chatter_count']."\n"; foreach($testobj['chatters'] as $key => $chatter){ echo "\n$key:\n"; foreach ($chatter as $value) { echo "$value\n"; } }
Output:
I get something like this from the URL you gave:
chatter_count:5461 moderators: emilydk fyzicul hnl hnlbot ngmack nixi93 psychostatik sodapoppin staystrong420 sxyhxy tastyphone staff: evoli pluto ... ... ...
这篇关于在多维数组上运行一个php foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!