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

2022-08-30 11:21:36

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

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

$foo = array(
  "bar1" => array(), // Should be encoded as an object
  "bar2" => array() // Should be encoded as an array
);

我想将其编码为:

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

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

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

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

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

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


答案 1

创建为对象。这将是区分它的唯一方法。它可以通过调用 来完成,或者用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":[]}

或通过类型转换:

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

答案 2

同样的答案,对于 .PHP5.4+

$foo = [
  "bar1" => (object)["",""],
  "bar2" => ["",""]
];

echo json_encode($foo);

另一个简单的例子,有一些重要的事情需要注意:

$icons = (object)["rain"=>["						

推荐