在多维数组上运行php foreach循环

时间:2016-10-17 04:51:24

标签: php arrays loops foreach

我需要在多维数组上运行foreach脚本。

原始JSON的格式如下:

{
    "_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"
        ]
    }
}

运行json_decode来获取PHP数据结构后,我现在迷失了如何运行foreach循环来输出类似的内容:

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

4 个答案:

答案 0 :(得分:3)

首先将json解码为数组,然后使用$key打印数组:

<?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";
    }
}

<强>输出:

我从您提供的网址中获得了类似的内容:

chatter_count:5461

moderators:
emilydk
fyzicul
hnl
hnlbot
ngmack
nixi93
psychostatik
sodapoppin
staystrong420
sxyhxy
tastyphone

staff:
evoli
pluto
...
...
...

答案 1 :(得分:0)

你只是落后于你想要完成的事情。要chatter_count使用$testobj ->chatter_count。然后循环使用chatters数组使用foreach($testobj->chatters as $key => $value) { // write your logic here }。通过这种方式,您可以获得您想要完成的任务。我可以在这里粘贴代码,但我希望您先尝试一下。希望你现在得到你的提示。

答案 2 :(得分:0)

<强> PHP

$data = json_decode($json, true);
echo "chatter_count: " . $data["chatter_count"] . "\n";
foreach($data['chatters'] as $chattersK=> $chatters) {
  echo $chattersK . ":\n";
  foreach($chatters as $chatterK => $chatters) {
     echo $chatters . "\n";
  }
  echo "\n";
}

演示:Eval.in

答案 3 :(得分:0)

试试这段代码 你必须添加一些打印样式。

$testobj = json_decode(file_get_contents("https://tmi.twitch.tv/group/user/sodapoppin/chatters"));
print("chatter_count:", $testobj->chatter_count);

foreach ( $testobj->chatters as $key=>$chatter )  
{  
print $key;  
foreach($chatter as $values){  
printf("%s\n", $values);  
 }  

}

希望这会对你有所帮助。