How to turn a json array created by PHP to javascript array

I’ve created a jason array using a PHP json_encode() function. The result looks like this:


Then I turn it into a javascript string (not sure) with this method:

	var mp3_tracks = '<?php echo json_encode($mp3_tracks); ?>';

I got the result as expected. However, when I extract javasacript values it looks ugly like this:

var track_1 = mp3_tracks[0]; // [
var song_1 = mp3_tracks[0].file; // undefined

When compare to this javascript array:

var mp3_tracks = [
var track_1 = mp3_tracks[0]; // Object {track: 0, name: "Song1", file: "Song1.mp3"} 
var song_1 = mp3_tracks[0].file; // Song1.mp3

How do I make the json block created created by PHP as javascript array.
Thank you


	var mp3_tracks = <?php echo json_encode($mp3_tracks); ?>;


Thanks, but the result is still the same. I’m pulling my hair off. (it was on chrome);

Well, on a second attempt. It’s kind of working. Still don’t know why???

Hi ketting00,

Are you sure you’ve removed the quote marks around the php tag which outputs the json?

Here’s the code I’m using to test this in Chrome, and it’s working properly:

$data = array(
    array("track" => 0, "name" => "Song1", "file" => "Song1.mp3"),
    array("track" => 1, "name" => "Song2", "file" => "Song2.mp3"),
    array("track" => 2, "name" => "Song3", "file" => "Song3.mp3")
<!DOCTYPE html>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
        var tracks = <?php echo json_encode($data); ?>;

Here’s my PHP code

$i = 0;
while(($row = $result->fetch_object()) && ($i <= 3)) {
	$mp3_tracks[] = array(
		'track' => $i++,
		'name' => str_replace(".".$mp3_title_extension,"",$mp3_title),
		'file' => str_replace(".".$mp3_path_extension,"",$mp3_path)

It is working now. Thank you,

Sounds like you need LIMIT 3 in your query :wink:

Thanks. I wasn’t thinking of that.