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

对于以下对象

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

 

posted @ 2015-09-30 10:36  DrWong  阅读(7263)  评论(0编辑  收藏  举报