HatoBrr
HatoBrr

Reputation: 353

foreach only displaying one JSON value

I have been struggling with foreach. It only gives me one result for the last element in an array.

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

}
?>

This is in my html code:

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

The result given is keeps repeating itself and not going thru the whole array.

Upvotes: 0

Views: 158

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

Oook, So you are running two loops on same data. In the first loop you populate some variables and then get out of that loop.

In the second loop you loop over all the rows again but instead of picking the values from there you use the variables you populated in your previous loop, which of course were overwritten on every iteration and you only see data for the last row.

Your first loop is useless, you only need 1 loop which might look like this

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

Upvotes: 1

Related Questions