PHP json_encode-JSON_FORCE_OBJECT混合对象和数组输出 [英] PHP json_encode - JSON_FORCE_OBJECT mixed object and array output

查看:243
本文介绍了PHP json_encode-JSON_FORCE_OBJECT混合对象和数组输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如,假设我具有以下数据结构:

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
);

我想将其编码为:

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

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

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

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

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

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

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

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

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

推荐答案

bar1创建为new stdClass()对象.这将是json_encode()区分它的唯一方法.可以通过调用new stdClass()或使用(object)array()

Create bar1 as 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()

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

这篇关于PHP json_encode-JSON_FORCE_OBJECT混合对象和数组输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆