2013-07-16 126 views
0

我目前正在玩弄一些PHP和JSON,我知道PHP的幾乎沒有什麼JSON,但我設法得到一半的地方,我需要目前我有這部分的代碼。Json到輸出數組的PHP問題

<?php 
$json = file_get_contents('http://eu.battle.net/api/wow/character/Ragnaros/Smoosher?fields=progression'); 
$data = json_decode($json, true); 

foreach ($data['progression']['raids'] as $raid) { 
    echo "Raid: ", $raid['name']; 
    echo " Normal: ", $raid['normal']; 
    echo " Heroic: ", $raid['heroic']; 
    echo " id: ", $raid['id']; 
    echo " Boss's: ", $raid['bosses']['name']; 
    ?> 
    <p> 
    <?php 
}; 

foreach ($data['progression']['raids']['bosses'] as $boss) { 
    echo " Boss Name: ", $boss['name']; 
} 

print_r($boss); 
#echo $data->name; 
?> 

現在第一的foreach工作正常,沒有任何問題,但是我注意到什麼它拉出來的數據到頁面罰款似乎是另一個(陣?)一個我在外面把所以首先我內試圖

echo " Boss's: ", $raid['bosses']['name']; 

這不過是老闆不守信的,並沒有從陣列中輸出,所以我想也許我需要另一個foreach語句,並開始拉動通過。然而,這部分

foreach ($data['progression']['raids']['bosses'] as $boss) { 
    echo " Boss Name: ", $boss['name']; 
} 

給出了一個錯誤

,我不能看到什麼即時做錯了:(任何幫助將是巨大的,JSON的IM從拉動是

http://eu.battle.net/api/wow/character/Ragnaros/Smoosher?fields=progression 

回答

2

你問題在於$data['progression']['raids']['bosses']不是陣列。

$data['progression']['raids']是一個ar陣列的光,而且每個陣列有一個bosses鍵,讓你的數據是這樣的:

$data['progression']['raids'][0]['bosses'] - 注意在那裏[0],而不是僅僅$data['progression']['raids']['bosses']

你應該巢環路上bosses內先前的循環,例如

<?php 
$json = file_get_contents('http://eu.battle.net/api/wow/character/Ragnaros/Smoosher?fields=progression'); 
$data = json_decode($json, true); 

foreach ($data['progression']['raids'] as $raid) 
{ 
echo "Raid: ", $raid['name']; 

echo " Normal: ", $raid['normal']; 

echo " Heroic: ", $raid['heroic']; 

echo " id: ", $raid['id']; 

foreach ($raid['bosses'] as $boss) 
{ 
    echo " Boss Name: ", $boss['name']; 
} 
?> 
<p> 
<?php 
}; 
+0

我看到多數民衆贊成在偉大的,應先試圖循環內循環之前問,但確實有助於噸謝謝。 –

+0

是啊被卡在一個計時器不得不等待5分鐘才能接受它:( –

1
$data['progression']['raids'] 

這個變量是一個數組。 你可以在這個數組中使用foreach。

foreach($data['progression']['raids'] as $raid) { 
    forach($raid['bosses'] as $boss) { 
     //here is your boss 
    } 
} 
1

你應該寫像這樣第二的foreach: - $數據[「進展」] [「襲擊」]保持陣列中它和[「老闆」]具有一個數組元素作爲成員爲$數據[ '進展'] [ '襲擊']。

foreach ($data['progression']['raids'] as $boss) 
foreach($boss['bosses'] as $boss1) 
{ 
    echo " Boss Name: ", $boss1['name']; 
    echo '<br>'; 
}