PHP json_encode 转换成空对象和空数组如何指定?

已邀请:

zkbhj - 凯冰科技站长

赞同来自:

对于以下对象:
$foo = array(
"bar1" => array(),
"bar2" => array()
);
我想转换成
{
"bar1": {},
"bar2": []
}
默认情况下用json_encode($foo)得到的是
{
"bar1": [],
"bar2": []
}
而加了JSON_FORCE_OBJECT参数的json_encode($foo,JSON_FORCE_OBJECT)得到的是
{
"bar1": {},
"bar2": {}
}
其实方法很简单

使用 new stdClass() 或是使用强制转换 (Object)array() 就行了.
$foo = array(
"bar1" => new stdClass(), // Should be encoded as an object
"bar2" => array() // Should be encoded as an array
);

echo json_encode($foo);
$foo = array(
"bar1" => (object)array(), // Should be encoded as an object
"bar2" => array() // Should be encoded as an array
);

echo json_encode($foo);
// {"bar1":{}, "bar2":[]}

要回复问题请先登录注册