Search code examples
phpmedia-library

How to create dynamic playlist.js for theme audio player using php?


This is a follow-up question, but I'll include the code from before. I have a playlist script...

     <script type="text/javascript">
var myPlaylist = [
 <?php
 foreach ($audiofiles as $file)
 {
   echo "{
        mp3:'".$file->guid."',
        title:'".$file->post_title."',
        artist:'"."',
        rating:5,
        buy:'".$file->post_excerpt."',
        price:'"."',
        duration:'"."',
        cover:'"."'
    },"
; }
?>
];
</script>

The problem, as you can probably see, is that the php puts a comma after the final audio file in the playlist, and that distupts the syntax and the whole thing doesn't load. I'm sure it's a simple fix, maybe create a different "echo" for the last item in the list? How would I do this?


Solution

  • $i = 0;
    foreach ($audiofiles as $file) {
      echo "{
        mp3: " . json_encode($file->guid) . ",
        title: " . json_encode($file->post_title) . ",
        artist: '',
        rating: 5,
        buy: " . json_encode($file->post_excerpt) . ",
        price: '',
        duration: '',
        cover: ''
      }";
      if ($i++ !== sizeof($audiofiles)-1) echo ",";
    }
    

    Are you sure you couldn't figure this out yourself?