PHP json_encode 转换成空对象和空数组

PHP json_encode 转换成空对象和空数组


对于如下对象html

$foo = array(
  "bar1" => array(), 
  "bar2" => array() 
);

我想转换成web

{
  "bar1": {},
  "bar2": []
}

默认状况下用json_encode($foo)获得的是json

{
  "bar1": [],
  "bar2": []
}

而加了JSON_FORCE_OBJECT参数的json_encode($foo,JSON_FORCE_OBJECT)获得的是数组

{
  "bar1": {},
  "bar2": {}
}

其实方法很简单svg

使用 new stdClass() 或是使用强制转换 (Object)array() 就好了.code

$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":[]}

文档转自:https://www.cnblogs.com/drwong/p/4848493.htmlxml