标签:
对于以下对象
$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":[]}
标签:
原文地址:http://www.cnblogs.com/drwong/p/4848493.html