2017 © Pedro PelΓ‘ez
 

library flattree

Adjacent list tree builder

image

marc/flattree

Adjacent list tree builder

  • Thursday, February 23, 2017
  • by marcioAlmada
  • Repository
  • 1 Watchers
  • 2 Stars
  • 25 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 1 Versions
  • 0 % Grown

The README.md

Build Status Coverage Status Latest Stable Version License , (*1)

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:, (*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

Non Recursive Adjacent List

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

Final Notes

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)

The Versions

23/02 2017

dev-master

9999999-dev

Adjacent list tree builder

  Sources   Download

MIT

The Requires

  • php 7.*

 

The Development Requires

tree