PHP 对象到 JSON : How to create class that will have multiple recursive children?

标签 php json recursion parent-child

我需要创建一个 PHP 类,该类将包含该类的多个父子关系,以便转换后的 JSON 字符串看起来与此类似。如果它的数组为空,我怎样才能让“ child ”不出现在 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 函数中,您可以更改序列化行为。在那里,您可以检查是否有任何 child ,并在需要时将他们留在外面。在这种情况下,您最终会得到这样的结果:

public function jsonSerialize() {
  $data = [
    "name" => $this->name,
    "code" => $this->code
  ];

  if(!empty($this->children)) {
    $data["children"] = $this->children;
  }

  return $data;
}

关于PHP 对象到 JSON : How to create class that will have multiple recursive children?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62532422/

相关文章:

PHP 和 SQL 照片库占位符图像

json - 如何在Fluter上从Firestore中的模型json数据内部序列化/建模

python - 井字游戏和 Minimax AI

c++ - 计算 (2^k)m=input 的递归函数

linux - 如何将 `chmod -R +w` 与 Ant、文件和文件夹一起使用?

php - 获取2个数字的百分比

javascript - 我似乎无法通过 xampp 的 ADMIN 按钮查看 mySQL 数据库

javascript - 用户在下拉框中选择 'others' 选项后从文本框中保存数据

javascript - .txt 文件和 .json 文件是否同样适用于存储 javascript 对象?

javascript - 嵌套 JSON 无法读取属性