0

我目前正在玩一些 php 和 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'];

它只输出boss's这个词,也没有从数组中输出任何内容,所以我想也许我需要另一个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
4

3 回答 3

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
};
于 2013-07-16T11:03:29.390 回答
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>';
 }
于 2013-07-16T11:13:21.220 回答
1
$data['progression']['raids']

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

foreach($data['progression']['raids'] as $raid) {
    forach($raid['bosses'] as $boss) {
        //here is your boss
    }
}
于 2013-07-16T11:04:55.207 回答