A simple helper package to allow using Trees on PHP

1.0.0 2018-04-05 14:55 UTC

This package is auto-updated.

Last update: 2024-11-05 06:50:42 UTC


README

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

Quick Installation

composer require danielcosta/tree

Usage

To use, just get an array like bellow

$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:

$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:

  • $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

paypal