当 php 中的数组为空时,json_encode 函数不返回大括号 {} [英] json_encode function not return Braces {} when array is empty in php

查看:25
本文介绍了当 php 中的数组为空时,json_encode 函数不返回大括号 {}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码

$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_encodeJSON_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆