php - PHP Object to JSON:如何创建具有多个递归子级的类?
问题描述
我需要创建一个 PHP 类,该类将具有该类的多个父子关系,以便转换后的 JSON 字符串看起来与此类似。如果 JSON 为空数组,如何让“孩子”不出现在 JSON 中?
{ name: "Element Parent",
code: "000"
children: [
{
name: "Element Child 1"
code: "001"
children: [
{
name: "Element Child 1A"
code: "001A"
},
{
name: "Element Child 1B"
code: "001B"
children: [
{
name: "Element Child 1BA"
code: "001BA"
}
]
}
]
}
,
{
name: "Element Child 2"
code: "002"
}
]
}
我正在尝试创建一个可以转换为上面的 JSON 字符串的 PHP 类。
<?php
class Element implements \JsonSerializable
{
private $name;
private $code;
public function __construct($name, $code, )
{
$this->name = $name;
$this->code = $code;
}
public function jsonSerialize()
{
return get_object_vars($this);
}
public function toJSON(){
return json_encode($this);
}
public $children[] = array(); // to contain Element children class
}
$element = new Element("Element Parent", 000);
$elementChild1 = new Element("Element Child 1", "001");
$elementChild1A = new Element("Element Child 1A", "001A");
$elementChild1B = new Element("Element Child 1B", "001B");
$elementChild1BA = new Element("Element Child 1BA", "001BA");
$elementChild1B->children[] = $elementChild1BA;
$elementChild1->children[] = $elementChild1A;
$elementChild1->children[] = $elementChild1B;
$element->children[] = elementChild1;
$elementChild2 = new Element("Element Child 2", "002");
$element->children[] = elementChild2;
echo $element->toJSON();
?>
非常感谢。
解决方案
在jsonSerialize
您实现的功能中,您可以更改序列化行为。在那里,您可以检查是否有孩子,并在需要时将其排除在外。在这种情况下,你最终会得到这样的结果:
public function jsonSerialize() {
$data = [
"name" => $this->name,
"code" => $this->code
];
if(!empty($this->children)) {
$data["children"] = $this->children;
}
return $data;
}
推荐阅读
- c++ - 如何存储用户输入到 for 循环中的值?
- google-drive-api - 提交同意屏幕进行验证是否会自动触发未经验证的应用屏幕?
- python - 关于 MTCNN 中的人脸检测,在 align_dataset_mtcnn.py 中。这是什么意思?
- php - 如何将 ReCAPTCHA 集成到 WORDPRESS 中的默认登录表单/评论中
- html - css位置绝对菜单顶部
- android - 如何在 Ionic 中跨页面传递数据?
- reactjs - 我正在尝试使用弹出版本的 create-react-app 设置 React 故事书
- c# - 数组乘对
- ansible - Ansible-在剧本中执行最后一个强制角色,即使执行流程中的任何先前角色都失败了
- javascript - 如何使用 ReactiveVar 在 Meteor 中的模板之间传递数据