foreach只显示一个JSON值

时间:2015-04-13 18:19:12

标签: php json foreach

我一直在与foreach挣扎。它只给出了一个数组中最后一个元素的结果。

if (isset($_POST['Title'])){
  $artist = $_POST['Title'];
  $artist = str_replace(' ', '%20', $artist);
  $Json = file_get_contents('http://developer.echonest.com/api/v4/song/search?api_key=HT72O1OINP8ERYDE9&artist='.$artist.'&bucket=audio_summary');
  $decode = json_decode($Json);

  $songList = array();

  foreach ($decode -> response -> songs as $song) 
  {
    $songList [] = array(
    $SongName  = $song->title,  
    $songId = $song->id,
    $artist = $song->artist_name,
    $bpm = $song->audio_summary->tempo
  );   
};

}
?>

这是我的HTML代码:

<?php  $i = 1;
foreach ($decode -> response -> songs as $test) {
  echo "<tr>
        <th>".$i."</th>
        <th>".$SongName."</th>
        <th>".$artist."</th>
        <th>".$time."</th>
        <th>".$bpm."</th></tr>";
  ++ $i;
}
?>

给出的结果是不断重复自身而不是通过整个数组。

1 个答案:

答案 0 :(得分:1)

Oook,所以你在相同的数据上运行两个循环。在第一个循环中,您填充一些变量,然后退出该循环。

在第二个循环中,您再次循环遍历所有行,但不是从那里选择值,而是使用您在上一个循环中填充的变量,当然在每次迭代时都会覆盖这些变量,而您只看到最后一行的数据

您的 第一个循环无用 ,您只需要一个可能看起来像这样的循环

   $i = 1;
    foreach ($decode -> response -> songs as $test) {echo 
                "<tr>
                <th>".$i."</th>
                <th>".$song->title."</th>
                <th>".$song->artist_name."</th>
                <th>".$time."</th>
                <th>".$song->audio_summary->tempo."</th></tr>";
                ++ $i;
    }
相关问题