PHP json_encode - JSON_FORCE_OBJECT混合对象和数组输出

Woo*_*ome 37 php json

我有一个PHP数据结构,我想要JSON编码.它可以包含许多空数组,其中一些需要编码为数组,其中一些需要编码为对象.

例如,假设我有这样的数据结构:

$foo = array(
  "bar1" => array(), // Should be encoded as an object
  "bar2" => array() // Should be encoded as an array
);
Run Code Online (Sandbox Code Playgroud)

我想把它编码成:

{
  "bar1": {},
  "bar2": []
}   
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用json_encode($foo, JSON_FORCE_OBJECT)我会得到对象:

{
  "bar1": {},
  "bar2": {}
}
Run Code Online (Sandbox Code Playgroud)

如果我使用json_encode($foo)我会得到数组:

{
  "bar1": [],
  "bar2": []
}
Run Code Online (Sandbox Code Playgroud)

有没有办法编码数据(或定义数组),所以我得到混合数组和对象?

Mic*_*ski 71

创建bar1new stdClass()对象.这将是json_encode()区分它的唯一方法.它可以通过调用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);
// {"bar1":{}, "bar2":[]}
Run Code Online (Sandbox Code Playgroud)

或通过类型转换:

$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":[]}
Run Code Online (Sandbox Code Playgroud)