开发者

Music playlist via PHP. json_encode() array limit?

开发者 https://www.devze.com 2023-01-19 06:26 出处:网络
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().

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 playlis开发者_开发问答t 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);
?>


  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...


Encode the track ID on 2 or even 3 digits using the php function sprintf with parameter %02d.

This worked fine for me.

0

精彩评论

暂无评论...
验证码 换一张
取 消