将json数组放在PHP中的json对象中

时间:2017-01-26 21:01:49

标签: php json

Hello Stackoverflow社区,我有点困惑,我怎么能实现这一目标。所以这就是我的json响应的样子:

some_array: [
    {
        some_json_object_atribute_1:
        some_json_object_atribute_2:
        // Here i need an array
        json_array: [

                    ]
    }
    {
        some_json_object_atribute_1:
        some_json_object_atribute_2:
    }
]

但我只从json数组中获取一行。这是代码的一部分:

$response["chat_rooms"] = array();

while ($chat_room = $result->fetch_assoc()) {
        $tmp = array();
        $tmp["chat_room_id"] = $chat_room["chat_room_id"];
        $unread_messages = $db->getAllUnreadMsgsFromChatRoom($user_id, $chat_room["chat_room_id"]);
        while ($unread_message = $unread_messages->fetch_assoc()) {
            // Here i need one json array
            $tmp["message_id"] = $unread_message["message_id"];
        }

        array_push($response["chat_rooms"], $tmp);
}

1 个答案:

答案 0 :(得分:0)

您在while循环的每次运行中都会覆盖$tmp["chat_room_id"]。 正确的语法是:

$tmp["chat_room_id"][] = $unread_message["message_id"];

array_push($tmp["chat_room_id"], $unread_message["message_id"]);