简体   繁体   English

PHP json_encode不会输出正确的结果

[英]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. 我想通过json对象输出用户,但是当我尝试输出他们的歌曲列表时,它只输出最后一个。 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: 我希望它输出这样的歌曲,但我很困惑如何使用PHP来做到这一点:

"songs":[{"title": "song1"}, {"title": "song2"}]
'favSongs' => array(
   'title' => 'song1',
   'title' => 'song2'
)

PHP will replace the 'title' key with the last one declared. PHP将用声明的最后一个键替换'title'键。

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

This is an array of objects, so in PHP it needs to be an array of arrays. 这是一个对象数组,因此在PHP中它需要是一个数组数组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM