2016-10-17 123 views
1

我需要在多維數組上運行一個foreach腳本。在多維數組上運行一個php 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 
+1

你到目前爲止嘗試過什麼? –

回答

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 
... 
... 
... 
0

你只是少數落後一步你要完成的任務。要獲得chatter_count請使用$testobj ->chatter_count。然後循環使用您的chatters陣列。這樣你就可以得到你想要完成的事情。我可以在這裏粘貼代碼,但我希望你先試一試。希望你現在得到你的提示。

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

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); 
} 

}

希望這可以幫助你。