dev-master
9999999-devAdjacent list tree builder
MIT
The Requires
- php 7.*
The Development Requires
tree
Wallogit.com
2017 © Pedro PelΓ‘ez
Adjacent list tree builder
composer require marc/flattree:dev-master
Consider you have the following adjacent list as data representing some recursive tree:, (*2)
| employee_id | parent_id | job_title | first_name |
|---|---|---|---|
| 1 | NULL | 'Managing Director' | 'Bill' |
| 2 | 1 | 'Customer Services' | 'Angela' |
| 3 | 1 | 'Development Manager' | 'Ben' |
| 4 | 2 | 'Assistant 1' | 'Henry' |
| 5 | 2 | 'Assistant 2' | 'Nicola' |
| 6 | 3 | 'Snr Developer' | 'Kerry' |
| 7 | 3 | 'Assistant' | 'James' |
| 8 | 6 | 'Jrn Developer' | 'Tim' |
To build a tree based on the given dataset, where parent_id=employee_id:, (*3)
use marc\flatrree\{unfold, debug};
$tree = unfold($associative_data, 'parent_id=employee_id');
echo debug($tree, "{job_title}: {first_name}");
Debug output:, (*4)
ββ <null>: <null> β ββ Managing Director: Bill β β ββ Customer Services: Angela β β β ββ Assistant 1: Henry β β β ββ Assistant 2: Nicola β β ββ Development Manager: Ben β β β ββ Snr Developer: Kerry β β β β ββ Jrn Developer: Tim β β β ββ Assistant: James
| id | class | animal | breed | size |
|---|---|---|---|---|
| 1 | 'mammal' | 'dog' | 'Dalmatian' | 'big' |
| 2 | 'mammal' | 'dog' | 'Bulldog' | 'small' |
| 3 | 'mammal' | 'dog' | 'Lhasa Apso' | 'small' |
| 4 | 'mammal' | 'cat' | 'Persian' | 'small' |
Build a tree grouping by class and animal:, (*5)
use marc\flattree\{unfold, debug};
$tree = unfold($data, ['class', 'animal']);
echo debug($tree, ['{:level}', '{:level}', '{breed}']);
Debug output:, (*6)
ββ mammal β ββ dog β β ββ Dalmatian β β ββ Bulldog β β ββ Lhasa Apso β ββ cat β β ββ Persian
One more level of grouping, now by class and animal and size:, (*7)
use marc\flattree\{unfold, debug};
$tree = unfold($associative_data, ['class', 'animal', 'size']);
echo debug($tree, ['{:level}', '{:level}', '{:level}', '{breed}']);
Debug output:, (*8)
ββ mammal β ββ dog β β ββ big β β β ββ Dalmatian β β ββ small β β β ββ Bulldog β β β ββ Lhasa Apso β ββ cat β β ββ small β β β ββ Persian
Notice marc\flattree\debug function is there for debug purposes only, you must not depend on its output., (*9)
Reference http://www.ibase.ru/files/articles/programming/dbmstrees/sqltrees.html, (*10)
Copyright (c) 2016-* MΓ‘rcio Almada. Distributed under the terms of an MIT-style license. See LICENSE for details., (*11)
Adjacent list tree builder
MIT
tree