如何使用 PHP 从数组创建嵌套 json

问题描述 投票:0回答:1
$my_array = array(
    "room" => array(
        array("id" =>"1", "message" => "This is a message") 
    )
);

echo json_encode($my_array, JSON_UNESCAPED_UNICODE); 

这是我得到的输出:

{"room":[{"id":"1","message":"This is a message"}]}

这是我想要得到的输出

{"room": { "id": 1, "message": "This is a message"}}`
php json
1个回答
0
投票

您正在数组中创建一个数组:

"room" => array(
    array("id" =>"1", "message" => "This is a message") 
)

内部数组具有命名键,它们被转换为 JSON 作为对象。但外层数组只是一个标准数组。

如果您不想将对象包装在数组中,请不要将其包装在数组中:

"room" => array("id" =>"1", "message" => "This is a message")
© www.soinside.com 2019 - 2024. All rights reserved.