当数组在php中为空时,json_encode函数不返回大括号{} [英] json_encode function not return Braces {} when array is empty in php
问题描述
我有这个代码
$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":[]}
This function return json:
{"message":"error","club_id":275,"status":"1","membership_info":[]}
但是我需要这样的json:
But I need json like this:
{"message":"error","club_id":275,"status":"1","membership_info":{}}
推荐答案
使用json_encode
的JSON_FORCE_OBJECT
选项:
json_encode($status, JSON_FORCE_OBJECT);
JSON_FORCE_OBJECT(整数) 使用非关联数组时,输出对象而不是数组.当输出的接收者期望对象并且数组为空时,此功能特别有用.自PHP 5.3.0起可用.
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.
或者,如果要在对象中保留其他"数组,则不要使用先前的答案,只需使用以下方法即可:
Or, if you want to preserve your "other" arrays inside your object, don't use the previous answer, just use this:
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=> new stdClass()
);
这篇关于当数组在php中为空时,json_encode函数不返回大括号{}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!