PHP Object to JSON: How to create class that will have multiple recursive children?

Viewed 139

I need to create a PHP Class that will multiple Parent-Child relationship of that Class so that the converted JSON string would look similar to this. And how can I make "children" not appear in JSON if its empty array?

{   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"
        }
    ]
}

I'm trying to create a PHP class that could be converted to the JSON String above.

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

?>

Thank you very much.

1 Answers

In the jsonSerialize function you implemented, you can change the serialization behaviour. There, you can check if there are any children and leave them out when desired. In this case, you'd end up with something like this:

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

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

  return $data;
}
Related