PhpTree is a PHP implementation of tree data structure that provides multiple trees implementations. The library also provides four trees traversals algorithm : In order, Post order, Pre Order, and Breadth first. In addition to exporters and importers such as Graph or simple text. The supported trees implementations include :
- Node: The base class.
- N-ary node: (or K-ary tree) extends the base class and allows you to specify the capacity of a node, the maximum children a node can have.
- Value node: extends the N-ary node and allows you to attach a value to the node.
- KeyValue node: extends the Value node and allows you to attach a key and a value to the node.
- Trie node: extends the KeyValue node, a simple Trie tree.
- Auto-balanced node: extends the N-ary node and tries to keep the tree as symetric as possible. It automatically balance all the children as soon as they are added.
- Merkle node: a tree in which every non-leaf node is labelled with the cryptographic hash of the labels of its child nodes.
Below simple usage of the PhpTree library
<?php declare(strict_types = 1); use Graphp\GraphViz\GraphViz; use drupol\phptree\Exporter\Graph; use drupol\phptree\Node\ValueNode; use drupol\phptree\Exporter\Text; include './vendor/autoload.php'; // Create the root node. $tree = new ValueNode('root', 2); $nodes = []; foreach (\range('A', 'Z') as $v) { $nodes[] = new ValueNode($v); } // Add children to the root node. $tree->add(...$nodes); // Export to an image. $graphViz = new GraphViz(); $graphExporter = new Graph(); $graphViz->display($graphExporter->export($tree)); // Export to text. $textExporter = new Text(); echo $textExporter->export($tree); // [root [A [C [G [O] [P]] [H [Q] [R]]] [D [I [S] [T]] [J [U] [V]]]] [B [E [K [W] [X]] [L [Y] [Z]]] [F [M] [N]]]]⏎
Exporters and importers supported by the library include :
- Ascii: Export a tree into an ascii graphic, just for swag and visualisation fun.
- Graph: Export a tree into a Graph using the graphp/graphp library.
- GraphViz: Export a tree into a script in GraphViz format.
- Text: Export a tree into a simple string, easy for storing in a database.
- nikic/php-ast: Import a tree from an AST generated by the PHP extension AST.
- nikic/php-parser: Import a tree from an AST generated by nikic/php-parser.
- microsoft/tolerant-php-parser: Import a tree from an AST generated by microsoft/tolerant-php-parser.
And finally Modifier:
- Reverse: To reverse a tree, all the children are mirrored.
PHPTree is an open source PHP library that requires PHP >= 7.1. Released under an MIT license. More information at https://github.com/drupol/phptree