"error", "club_id"=>$_club_id, -6ren">
gpt4 book ai didi

php - 当php中的数组为空时,json_encode函数不返回大括号{}

转载 作者:IT老高 更新时间:2023-10-28 12:49:35 25 4
gpt4 key购买 nike

我有这个代码

$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>array(),
);

echo json_encode($status);

这个函数返回json:
{"message":"error","club_id":275,"status":"1","membership_info":[]}

但我需要这样的 json:

{"message":"error","club_id":275,"status":"1","membership_info":{}}

最佳答案

使用 json_encodeJSON_FORCE_OBJECT 选项:

json_encode($status, JSON_FORCE_OBJECT);

Documentation

JSON_FORCE_OBJECT (integer) Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.

或者,如果你想在你的对象中保留你的“其他”数组,不要使用前面的答案,只需使用这个:

$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=> new stdClass()
);

关于php - 当php中的数组为空时,json_encode函数不返回大括号{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28189390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com