$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":[]} $obj = (object)[]; if ($obj) { //空对象 返回yes exit('yes'); } else { exit('no'); } $array = []; if ($array) { //空数组 返回no exit('yes'); } else { exit('no'); }
默认情况下用json_encode($foo)得到的是
{ "bar1": [], "bar2": [] }
而加了JSON_FORCE_OBJECT参数的json_encode($foo,JSON_FORCE_OBJECT)得到的是
{ "bar1": {}, "bar2": {} }