-1

Apologies if this has answers using a different terminology; I've been searching around but can't find an answer to this question.

I'm trying to add results from an SQL query as a nested array within another array. The parent array looks like this:

    $room=[
        "id" => $roomID,
        "name" => $roomName,
        "desc" => $roomDesc,
        "tracks" => [
            //SQL Results here!
            track {
              //Track ID,
              //Track Name,
              //Track Artist,
              //Track URL,
            },
            track {
              //Track ID,
              //Track Name,
              //Track Artist,
              //Track URL,
            }, 
        ]
    ];

I'm not sure how to add a sub-array of tracks into this array however. Currently I'm creating an array like this:

  $rows = array();
  //SQL Call logic here
      if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
          $row_array['id'] = $row['id'];
          $row_array['track_name'] = $row['track_name'];
          $row_array['track_artist'] = $row['track_artist'];
          $row_array['track_url'] = $row['track_url'];
          array_push($rows,$row_array);
        }
        print_r(json_encode($rows));
      } else {
          echo "Error: Tracks not found";
          return;
          $conn->close();
          die();
      }

I'm looking to have each SQL result as a "track" object within the "tracks" array in $room, I just don't know how!

Shadow
  • 33,525
  • 10
  • 51
  • 64
  • Possible duplicate of [How to add elements to an empty array in PHP?](https://stackoverflow.com/questions/676677/how-to-add-elements-to-an-empty-array-in-php) – Peter Apr 08 '18 at 13:33
  • 1
    `$room['tracks'][] = $row_array;` – Peter Apr 08 '18 at 13:34

1 Answers1

0

You could add directly your data into $room['tracks'], inside the loop:

while($row = $result->fetch_assoc()) {
    $row_array['id'] = $row['id'];
    $row_array['track_name'] = $row['track_name'];
    $row_array['track_artist'] = $row['track_artist'];
    $row_array['track_url'] = $row['track_url'];
    $room['tracks'][] = $row_array ;
}
print_r(json_encode($room));

Or, if $row contains only the keys you want to add, you could do:

while($row = $result->fetch_assoc()) {
    $room['tracks'][] = $row ;
}
print_r(json_encode($room));
Syscall
  • 19,327
  • 10
  • 37
  • 52