1

I'm using JSON_encode to send data to a js file for tracks. A user could have one or several tracks so that's where the problem lies. Not sure how to organise my array to allow for several arrays. I can't use an array within an array since all the JSON data needs to be separated preferably so there will be something like;

track1 {ID:110232....}
track2 {ID:21402....}

What I have now works fine if there is just one track.

$ID = $_GET['ID'];
$result = mysql_query("SELECT * FROM tracks WHERE ID = '$ID' ORDER BY timestamp DESC");
while($row = mysql_fetch_array($result)){
    $T_ID = $row['T_ID'];
    $T_url = $row['url'];
    $T_name = $row['name'];
    $T_timestamp = $row['timestamp'];
    $arr = array('T_ID' => $ID,'T_name' => $T_name, 'T_url' => $T_url, 'T_timestamp' => $T_timestamp );

    echo json_encode($arr);
}
2

1 Answer 1

4

Why can't you use an (associative) array inside an container array like this:

$cont = array();
while($row = mysql_fetch_array($result)){
  $T_ID = $row['T_ID'];
  $T_url = $row['url'];
  $T_name = $row['name'];
  $T_timestamp = $row['timestamp'];
  $arr = array('T_ID' => $ID,'T_name' => $T_name, 'T_url' => $T_url, 'T_timestamp' => $T_timestamp );

  $cont[] = $arr;
}

echo json_encode($cont);

This results in a JSON structure like this, which keeps all your tracks in separate objects:

[ 
  {'T_ID': 1, 'T_name': 1, ... },
  {'T_ID': 2, 'T_name': 2, ... },
  {'T_ID': 3, 'T_name': 3, ... },
  ...
]

As noted in the comments you should switch to PDO or mysqli- functions, but this doesn't matter for the problem at hand..

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks very much. I know this isn't part of the problem discussed but how would i return the results of all the JSON arrays in jQuery?
@nbs189 jQuery has the parseJSON() function, which transforms the JSON string into a JavaScript object, which you can then use as you like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.