Json To PHP发出输出数组的问题

时间:2013-07-16 11:00:11

标签: php json

我目前正在使用一些php和JSON,我知道PHP的abit几乎没有JSON,但我已经成功地获得了目前我需要的部分代码。

<?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'];

除了单词boss之外什么都不输出,而且数组中没有任何内容,所以我想也许我需要另一个foreach语句并开始拉动它。不过这部分

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

给出错误

Warning: Invalid argument supplied for foreach() in xxxxxx/xx/xxxxx/wow/test.php on line 22

我无法看到我做错了什么:(任何帮助都会很棒,json我会从中拉出来

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

3 个答案:

答案 0 :(得分:2)

这里的问题是$data['progression']['raids']['bosses']不是数组。

$data['progression']['raids']是一个数组数组,每个数组都有一个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
};

答案 1 :(得分:1)

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

此变量是一个数组。 你可以在这个数组中使用foreach。

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

答案 2 :(得分:1)

你应该这样写第二个foreach: - $ data ['progression'] ['raids']在其中保存数组,['bosses']有一个数组元素作为$ data ['progression'] ['raids']的成员。

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