對於以下對象
$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":[]}