views:

44

answers:

1

Hola!

Im using PHP to create a playlist. Two random songs are chosen from a directory, and their name and location are stored in an array and then written to a file via json_encode().

$arraySongs[] = array('name' => $songName , 'mp3' => $webUrl);

This works great. I can make a very long playlist, two songs at a time. Id also like to remove songs, so I have an AJAX powered delete button, that posts the id of the track to be deleted, PHP then loads the whole tracklist...

$decoded = json_decode(file_get_contents($tracklist),true);

and removes the given song from the array, then re encodes and re writes the json text file. This all works great.

The problem comes whenever I try to delete anything with a playlist of more than 10 items.

Typically, my song.json file goes [{name:song1,mp3:song url},{name:song2,mp3:song2 url}] However, when I have a list of more than 10 items, the re encoded playlist looks like this:

[{ ... },{name:song9,mp3:song9 url}],[10,{"name":song10,mp3:song10 url}]

Why is my re-encoded array get that strange [10,{"name"... [11,{"name"... [12,{"name"... but everything below 10 is always fine?

Thanks for reading this! Any suggestions would be greatly appreciated, this is driving me nuts!

Here is the code im Using:

<?php
$json = "song.php";
$decoded = json_decode(file_get_contents($json),true);
$playlist = array();
$names = array();

// Now Get i From Javascript
$i=$_POST['id'];

//Select i's Array
$collect_array=$decoded[$i];
    while (list ($key, $val) = each ($collect_array)) {
//Remove i's Values
//echo "<br />$key -> $val <br>";
unset($decoded[$i]);
}
//Take all the remaining arrays
$collect_array=$decoded;
    while (list ($key, $val) = each ($collect_array)) {
$arraySongs[] = array($key , $val);
}
// Our New Array ready for json.
$jsonData = json_encode($arraySongs);
// open song.php and scribble it down
$tracklist = $json;
$fh = fopen($tracklist, 'w') or die("can't open filename: $tracklist");
fwrite($fh, $jsonData);
fclose($fh);
?>
A: 
  1. try removing elements with unset
  2. debug your code (not posted in the thread, so do it yourself) by adding a line where you var_dump or print_r the whole thing before json_encode

or it's a bug in json_encode which would not be nice...

naugtur