jamcoupe
jamcoupe

Reputation: 1452

PHP json_encode won't output proper result

I want to output users via a json object but when I try to output their songs list it only outputs the last one. I want to get this list into an array.

this is my array push while looping through users,

array_push($arrayUsers, array(
               'username' => $user['username'],
               'id' => $user['_id'],
               'favSongs' => array(
                    'title' =>'song1',
                    'title' =>'song2'
                    )
               )
          );

but this is what I get back (missing song title),

[{"username":"asdfasdfasd","id":{"$id":"4f58d7227edae19c02000000"},"songs":{"title":"song2"}}]

I want it to output the songs like this, but am confused how to get it to do this using PHP:

"songs":[{"title": "song1"}, {"title": "song2"}]

Upvotes: 1

Views: 108

Answers (1)

gen_Eric
gen_Eric

Reputation: 227180

'favSongs' => array(
   'title' => 'song1',
   'title' => 'song2'
)

PHP will replace the 'title' key with the last one declared.

"songs":[{"title": "song1"}, {"title": "song2"}]

This is an array of objects, so in PHP it needs to be an array of arrays.

'favSongs' => array(
   array('title' => 'song1'),
   array('title' => 'song2')
)

Upvotes: 3

Related Questions