PHPackages                             bluem/tree - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. bluem/tree

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

bluem/tree
==========

Library for handling tree structures based on parent IDs

4.0(9mo ago)252916.1k↓10.8%46[1 PRs](https://github.com/BlueM/Tree/pulls)7BSD-3-ClausePHPPHP &gt;=8.2CI passing

Since Jun 26Pushed 9mo ago17 watchersCompare

[ Source](https://github.com/BlueM/Tree)[ Packagist](https://packagist.org/packages/bluem/tree)[ Docs](https://github.com/BlueM/Tree)[ RSS](/packages/bluem-tree/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (4)Versions (17)Used By (7)

[![Build status](https://github.com/BlueM/Tree/actions/workflows/php.yml/badge.svg)](https://github.com/BlueM/Tree/actions/workflows/php.yml/badge.svg)

Overview
========

[](#overview)

This library provides handling of data that is structured hierarchically using parent ID references. A typical example is a table in a relational database where each record’s “parent” field references the primary key of another record. Of course, usage is not limited to data originating from a database, but anything: you supply the data, and the library uses it, regardless of where the data came from and how it was processed.

It is important to know that the tree structure created by this package is *read-only*: you can’t use it to perform modifications of the tree nodes.

On the other hand, one nice thing is that it’s pretty fast. This does not only mean the code itself, but also that the constructor takes the input data in a format that is simple to create. For instance, to create a tree from database content, a single `SELECT` is sufficient, regardless of the depth of the tree and even for thousands of nodes.

Installation
============

[](#installation)

The recommended way to install this library is through [Composer](https://getcomposer.org): `composer require bluem/tree`. As the library uses [semantic versioning](http://semver.org), you can define a version constraint in `composer.json` which allows all non-major updates.

Alternatively, you can clone the repository using git or download a tagged release.

Usage
=====

[](#usage)

Creating a tree
---------------

[](#creating-a-tree)

```
// Create the tree with an array of arrays (or use an array of Iterators,
// Traversable of arrays or Traversable of Iterators):
$data = [
    ['id' => 1, 'parent' => 0, 'title' => 'Node 1'],
    ['id' => 2, 'parent' => 1, 'title' => 'Node 1.1'],
    ['id' => 3, 'parent' => 0, 'title' => 'Node 3'],
    ['id' => 4, 'parent' => 1, 'title' => 'Node 1.2'],
];
$tree = new BlueM\Tree($data);

// When using a data source that uses different keys for "id" and "parent",
// or if the root node ID is not 0 (in this example: -1), use Tree’s argument 2.
$data = [
    ['nodeId' => 1, 'parentId' => -1, 'title' => 'Node 1'],
    ['nodeId' => 2, 'parentId' => 1, 'title' => 'Node 1.1'],
    ['nodeId' => 3, 'parentId' => -1, 'title' => 'Node 3'],
    ['nodeId' => 4, 'parentId' => 1, 'title' => 'Node 1.2'],
];
$tree = new BlueM\Tree(
    $data,
    new Bluem\Tree\Options(rootId: -1, idFieldName: 'nodeId', parentIdFieldName: 'parentId'),
);
```

Updating the tree with new data
-------------------------------

[](#updating-the-tree-with-new-data)

```
// Rebuild the tree from new data
$tree->rebuildWithData($newData);
```

Retrieving nodes
----------------

[](#retrieving-nodes)

```
// Get the top-level nodes (returns array)
$rootNodes = $tree->getRootNodes();

// Get all nodes (returns array)
$allNodes = $tree->getNodes();

// Get a single node by its unique identifier
$node = $tree->getNodeById(12345);
```

Getting a node’s parent, siblings, children, ancestors and descendants
----------------------------------------------------------------------

[](#getting-a-nodes-parent-siblings-children-ancestors-and-descendants)

```
// Get a node's parent node (will be null for the root node)
$parentNode = $node->getParent();

// Get a node's siblings as an array
$siblings = $node->getSiblings();

// Ditto, but include the node itself (identical to $node->getParent()->getChildren())
$siblings = $node->getSiblingsAndSelf();

// Get a node's preceding sibling (null, if there is no preceding sibling)
$precedingSibling = $node->getPrecedingSibling();

// Get a node's following sibling (null, if there is no following sibling)
$followingSibling = $node->getFollowingSibling();

// Does the node have children?
$bool = $node->hasChildren();

// Get the number of Children
$integer = $node->countChildren();

// Get a node's child nodes
$children = $node->getChildren();

// Get a node's ancestors (parent, grandparent, ...)
$ancestors = $node->getAncestors();

// Ditto, but include the node itself
$ancestorsPlusSelf = $node->getAncestorsAndSelf();

// Get a node's descendants (children, grandchildren, ...)
$descendants = $node->getDescendants();

// Ditto, but include the node itself
$descendantsPlusSelf = $node->getDescendantsAndSelf();
```

Accessing a node’s properties
-----------------------------

[](#accessing-a-nodes-properties)

```
// Get a node's ID
$id = $node->getId();

// Get the node's hierarchical level (1-based)
$level = $node->getLevel();

// Access node properties using get() overloaded getters or __get():
$value = $node->get('myproperty');
$value = $node->myproperty;
$value = $node->getMyProperty();

// Get the node's properties as an associative array
$array = $node->toArray();

// Get a string representation (which will be the node ID)
echo "$node";
```

Using the library with non-default options
------------------------------------------

[](#using-the-library-with-non-default-options)

`Tree` uses defaults, which are defied in `\BlueM\Tree\Options`. If any of those defaults does not fit your needs, you can customize it.

For example, if the field which holds the parent node’s ID in your data is not called “parent”, but “parent\_id”, you could specify it like this:

```
$tree = new BlueM\Tree($nodesData, new \BlueM\Tree\Options(parentIdFieldName: 'parent_id'));
```

Example: Using it with literal data
-----------------------------------

[](#example--using-it-with-literal-data)

```
