1

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"}]
3
  • 1
    array('title' =>'song1','title' =>'song2') is not a valid array - or rather it is valid but you cannot have two of the same key without always overwriting one. Commented Mar 9, 2012 at 19:58
  • Instead, just use a plain numeric array for those 'favSongs' => array('song1','song2') Commented Mar 9, 2012 at 19:59
  • 1
    ohhh I get it now! Thanks I tried this and it worked array_push($arrayUsers, array('username' => $user['username'], 'id' => $user['_id'], 'favSongs' => array(array('title' =>'song1'), array('title' =>'song3')))); Commented Mar 9, 2012 at 20:01

1 Answer 1

3
'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')
)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.