marc/flattree

Adjacent list tree builder

dev-master 2017-02-23 18:27 UTC

This package is auto-updated.

Last update: 2024-12-18 06:46:01 UTC


README

Build Status Coverage Status Latest Stable Version License

Set Up

composer require marc/flattree:dev-master

Usage

Recursive Adjacent List

Consider you have the following adjacent list as data representing some recursive tree:

To build a tree based on the given dataset, where parent_id=employee_id:

use marc\flatrree\{unfold, debug};

$tree = unfold($associative_data, 'parent_id=employee_id');

echo debug($tree, "{job_title}: {first_name}");

Debug output:

├─ <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

Non Recursive Adjacent List

Build a tree grouping by class and animal:

use marc\flattree\{unfold, debug};

$tree = unfold($data, ['class', 'animal']);

echo debug($tree, ['{:level}', '{:level}', '{breed}']);

Debug output:

├─ mammal
│  ├─ dog
│  │  └─ Dalmatian
│  │  └─ Bulldog
│  │  └─ Lhasa Apso
│  ├─ cat
│  │  └─ Persian

One more level of grouping, now by class and animal and size:

use marc\flattree\{unfold, debug};

$tree = unfold($associative_data, ['class', 'animal', 'size']);

echo debug($tree, ['{:level}', '{:level}', '{:level}', '{breed}']);

Debug output:

├─ mammal
│  ├─ dog
│  │  ├─ big
│  │  │  └─ Dalmatian
│  │  ├─ small
│  │  │  └─ Bulldog
│  │  │  └─ Lhasa Apso
│  ├─ cat
│  │  ├─ small
│  │  │  └─ Persian

Final Notes

Notice marc\flattree\debug function is there for debug purposes only, you must not depend on its output.

Reference http://www.ibase.ru/files/articles/programming/dbmstrees/sqltrees.html

Copyright

Copyright (c) 2016-* Márcio Almada. Distributed under the terms of an MIT-style license. See LICENSE for details.