PHPackages                             dominator/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. dominator/tree

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

dominator/tree
==============

Library for handling tree structures based on parent IDs, e.g. a self-joined database table

2.1(7y ago)021BSD-2-ClausePHPPHP =5.6

Since Jun 26Pushed 7y ago1 watchersCompare

[ Source](https://github.com/dominator88/Tree)[ Packagist](https://packagist.org/packages/dominator/tree)[ Docs](https://github.com/dominator88/Tree)[ RSS](/packages/dominator-tree/feed)WikiDiscussions master Synced 4d ago

READMEChangelog (1)Dependencies (2)Versions (14)Used By (0)

[![Build Status](https://camo.githubusercontent.com/27d3494867d226b6518eb29236bb5732792c7a1bb7c143498d6c2d23a68087f9/68747470733a2f2f7472617669732d63692e6f72672f426c75654d2f547265652e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/BlueM/Tree)[![SensioLabsInsight](https://camo.githubusercontent.com/848a93878d7b018ffa7361e13034e4aadd52db275d43b10b0e839c2527c50bd0/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f35383464323065322d636436322d346165642d386430392d6238376562373230303564322f6d696e692e706e67)](https://insight.sensiolabs.com/projects/584d20e2-cd62-4aed-8d09-b87eb72005d2)

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. If you need a library for that, you might want to take a look at [nicmart/tree](https://github.com/nicmart/Tree).

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 preferred way to install Tree is through [Composer](https://getcomposer.org). For this, simply execute `composer require bluem/tree` (depending on your Composer installation, it could be “composer.phar” instead of “composer”) and everything should work fine. *Or* you manually add`"bluem/tree": "~2.0"` to the dependencies in your `composer.json` file and subsequently install/update dependencies.

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

Updating
--------

[](#updating)

As this library uses [semantic versioning](http://semver.org), you will get fixes and feature additions when running `composer update`, but not changes which break the API.

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 the options
// array you can pass to the constructor:
$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,
    ['rootId' => -1, 'id' => 'nodeId', 'parent' => '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
$bool = $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";
```

Example: Using it with a self-joined database table
---------------------------------------------------

[](#example--using-it-with-a-self-joined-database-table)

```
