PHP Helper - Tree
![Software License][ico-license]
![Coverage Status][ico-scrutinizer]
![Total Downloads][ico-downloads], (*1)
Quick Installation
composer require danielcosta/tree
Usage
To use, just get an array like bellow, (*2)
$flatArray = [
[
'id' => 1,
'name' => 'Level 1',
'parentId' => 0,
'nodes' => [],
],
[
'id' => 3,
'name' => 'Level 3',
'parentId' => 2,
'nodes' => [],
],
[
'id' => 2,
'name' => 'Level 2',
'parentId' => 1,
'nodes' => [],
],
];
And pass it to the helper Tree
, using Tree::makeFromFlatArray($flatArray);
. The result will be exactly this:, (*3)
$result = Tree::makeFromFlatArray($flatArray);
print_r($result);
/*
Array
(
[id] => 1
[name] => Level 1
[parentId] => 0
[nodes] => Array
(
[0] => Array
(
[id] => 2
[name] => Level 2
[parentId] => 1
[nodes] => Array
(
[0] => Array
(
[id] => 3
[name] => Level 3
[parentId] => 2
[nodes] => Array
(
)
)
)
)
)
)
*/
Optional parameters to this method are:, (*4)
- $parentId = 0 - when you want to set the first level of the return
- string $key = 'id' - the primary key on your flat array
- string $parentKey = 'parentId' - the parent key on your flat array
- string $childKey = 'nodes' - where to put the child nodes
Buy me a coffee
, (*5)