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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11670575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:50:49  来源:igfitidea点击:

PHP json_encode - JSON_FORCE_OBJECT mixed object and array output

phpjson

提问by Woodgnome

I have a PHP data structure I want to JSON encode. It can contain a number of empty arrays, some of which need to be encoded as arrays and some of which need to be encoded as objects.

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

For instance, lets say I have this data structure:

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

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

I would like to encode this into:

我想将其编码为:

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

But if I use json_encode($foo, JSON_FORCE_OBJECT)I will get objects as:

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

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

And if I use json_encode($foo)I will get arrays as:

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

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

Is there any way to encode the data (or define the arrays) so I get mixed arrays and objects?

有什么方法可以对数据进行编码(或定义数组),以便混合数组和对象?

回答by Michael Berkowski

Create bar1as a new stdClass()object. That will be the only way for json_encode()to distinguish it. It can be done by calling new stdClass(), or casting it with (object)array()

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

OR by typecasting:

或通过类型转换:

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

回答by NVRM

Same answer, for php7+ and php 5.4.

相同的答案,对于 php7+ 和 php 5.4。

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

echo json_encode($foo);

回声 json_encode($foo);

回答by Mike Brant

There answer is no. There is no way for the function to guess your intent as to which array should be array and which should be objects. You should simply cast the arrays you want as object before json_encoding them

答案是否定的。该函数无法猜测您的意图,即哪个数组应该是数组,哪些应该是对象。您应该在 json_encoding 它们之前简单地将您想要的数组转换为对象