|
| 1 | +# Tree |
| 2 | + |
| 3 | +A PHP library for working with tree data structures. |
| 4 | + |
| 5 | +## Installation |
| 6 | + |
| 7 | +```shell |
| 8 | +$ composer require plook/tree |
| 9 | +``` |
| 10 | + |
| 11 | +## Working with trees that are stored in arrays |
| 12 | + |
| 13 | +### Traversing a left/right tree that is ordered by the left value |
| 14 | + |
| 15 | +```php |
| 16 | +$tree = [ |
| 17 | + ['id' => 1, 'left' => 1, 'right' => 14], |
| 18 | + ['id' => 2, 'left' => 2, 'right' => 7], |
| 19 | + ['id' => 3, 'left' => 3, 'right' => 4], |
| 20 | + ['id' => 4, 'left' => 5, 'right' => 6], |
| 21 | + ['id' => 5, 'left' => 8, 'right' => 13], |
| 22 | + ['id' => 6, 'left' => 9, 'right' => 10], |
| 23 | + ['id' => 7, 'left' => 11, 'right' => 12], |
| 24 | +]; |
| 25 | + |
| 26 | +/** @var TraverseLeftRightTree<array{id: int, left: int, right: int}> $traverse */ |
| 27 | +$traverse = new TraverseLeftRightTree(); |
| 28 | + |
| 29 | +$traverse( |
| 30 | + $tree, |
| 31 | + 'left', |
| 32 | + 'right', |
| 33 | + static function (array $node): void { |
| 34 | + echo sprintf('Processing node %s%s', $node['id'], PHP_EOL); |
| 35 | + }, |
| 36 | + static function (array $node): void { |
| 37 | + echo sprintf('Childrens of node %s have been processed%s', $node['id'], PHP_EOL); |
| 38 | + }, |
| 39 | +); |
| 40 | +``` |
| 41 | + |
| 42 | +```text |
| 43 | +Processing node 1 |
| 44 | +Processing node 2 |
| 45 | +Processing node 3 |
| 46 | +Childrens of node 3 have been processed |
| 47 | +Processing node 4 |
| 48 | +Childrens of node 4 have been processed |
| 49 | +Childrens of node 2 have been processed |
| 50 | +Processing node 5 |
| 51 | +Processing node 6 |
| 52 | +Childrens of node 6 have been processed |
| 53 | +Processing node 7 |
| 54 | +Childrens of node 7 have been processed |
| 55 | +Childrens of node 5 have been processed |
| 56 | +Childrens of node 1 have been processed |
| 57 | +``` |
0 commit comments