/** * This method checks that the method used to convert a tree to an array works as expected. */ public function testToArray() { $fixture = $this->__fixturesDir . DIRECTORY_SEPARATOR . 'treeAsJson.json'; $this->assertJsonStringEqualsJsonFile($fixture, json_encode($this->__treeByData->toArray())); $this->assertJsonStringEqualsJsonFile($fixture, json_encode($this->__treeByObjects->toArray())); $this->assertJsonStringEqualsJsonFile($fixture, json_encode(Tree::fromArray($this->__treeAsArray)->toArray())); $serializer = function ($v) { return self::__dataSerializer($v); }; $fixture = $this->__fixturesDir . DIRECTORY_SEPARATOR . 'treeSerializedAsJson.json'; $this->assertJsonStringEqualsJsonFile($fixture, json_encode($this->__treeByData->toArray($serializer))); $this->assertJsonStringEqualsJsonFile($fixture, json_encode($this->__treeByObjects->toArray($serializer))); $this->assertJsonStringEqualsJsonFile($fixture, json_encode(Tree::fromArray($this->__treeAsArray)->toArray($serializer))); }
<?php /** * This example shows how to convert a tree defined as an object of class \dbeurive\Tree\Tree into the "array representation" (an array of imbricated arrays). */ include __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php'; use dbeurive\Tree\Tree; $tree = new Tree("getRoot"); $tree->getRoot()->addChild("A")->end()->addChild("B")->end()->addChild("C")->addChild("D")->addChild("E")->addChild("EE")->end()->addChild("EEE")->end()->end()->addChild("F")->end()->end()->addChild("A")->addChild('H')->addChild("I")->addChild("J")->addChild("K")->end()->addChild("L")->end()->end()->end()->end()->end()->end(); $array = $tree->toArray(); print print_r($array, true) . "\n";