PHPackages                             landlib/treealgorithms - 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. landlib/treealgorithms

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

landlib/treealgorithms
======================

This group of methods for work with tree structure. Provide methods build tree from flat array, find node in the tree by id, walk tree and execulte callback function for each node. Node of the tree has fields like as id, parent\_id, children. Concrete names of the tree node fields can be configured with TreeAlgorithms properties idFieldName, parentIdFieldName, childsFieldName. Also exists javascript release, search lamzin-andrey/landlib on github.

031PHP

Since Aug 23Pushed 4y ago1 watchersCompare

[ Source](https://github.com/lamzin-andrey/treealgorithms)[ Packagist](https://packagist.org/packages/landlib/treealgorithms)[ RSS](/packages/landlib-treealgorithms/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependenciesVersions (1)Used By (0)

En
==

[](#en)

TreeAlgorithms
--------------

[](#treealgorithms)

This group of methods for work with tree structure. Provide methods build tree from flat array, find node in the tree by id, walk tree and execulte callback function for each node. Node of the tree has fields like as `id`, `parent_id`, `children`. Concrete names of the tree node fields can be configured with TreeAlgorithms properties `idFieldName`, `parentIdFieldName`, `childsFieldName`. Also exists javascript release . Interfaces of javascript object and this php class is full compatible.

### getBranchIdList($node)

[](#getbranchidlistnode)

Resursive walk all children nodes of the node and return array of integer with `TreeAlgorithms::$idFieldName` values.

In example

```
	$sFieldName = TreeAlgorithms::$idFieldName;
	$id = $node->$sFieldName;
```

`$id` containts into result array in the zero position.

### walkAndExecuteAction($oTree, $oCallback)

[](#walkandexecuteactionotree-ocallback)

Walk all nodes $oTree and execute callback for each node. Node pass as argument to the callback.

$oCallback must be object

```
//... in your class method body ...

$oCallback = new StdClass();
$oCallback->context = $this; //or static
$oCallback->f = 'yourClassMethodName';
$oCallback->isStatic = true; //or false if need static class
```

You can not set `isStatic` field if context will pointer on the class object ($this).

### buildTreeFromFlatList($aScopeArgs, $bSetChildsAsArray = false)

[](#buildtreefromflatlistascopeargs-bsetchildsasarray--false)

Build tree from "flat" `array` argument `aScopeArgs`.

For example, $aScopeArgs can be like:

```
$aFlatList = [
	[
		'id' => 1,
		'name' =>  'Books',
		'parent' => 0
	],
	[
		'id' => 2,
		'name' => 'Sciences',
		'parent' => 1
	],
	[
		'id' => 3,
		'name' => 'Adventure',
		'parent' => 1
	],
	[
		'id' => 4,
		'name' => 'Computer Sciences',
		'parent' => 2
	]
];
```

Then code:

```
TreeAlgorithms::$parentIdFieldName = 'parent';
TreeAlgorithms::$childsFieldName = 'inners';
$aTrees = TreeAlgorithms::buildTreeFromFlatList($aFlatList);
//$aTrees[0] will containt our tree
```

return array:

```
[
	[
		'id' => 1,
		'name' => "Books",
		'parent' => 0,
		'inners' => {//(StdClass)
			'2' => [
				'id' => 2,
				'name' => 'Sciences',
				'parent' => 1,
				'inners' => {//(StdClass)
					'4' => [
						'id' => 4,
						'name' => 'Computer Sciences',
						'parent' => 2
					]
				}
			],
			'3' => [
				'id' => 3,
				'name' => 'Adventure',
				'parent' => 1
			]
		}
	]
]
```

If you pass second argument `TreeAlgorithms.buildTreeFromFlatList(aFlatList, true)` result will be:

```
[
	[
		'id' => 1,
		'name' => "Books",
		'parent' => 0,
		'inners' => [
			'2' => [
				'id' => 2,
				'name' => 'Sciences',
				'parent' => 1,
				'inners' => [
					'4' => [
						'id' => 4,
						'name' => 'Computer Sciences',
						'parent' => 2
					]
				]
			],
			'3' => [
				'id' => 3,
				'name' => 'Adventure',
				'parent' => 1
			]
		]
	]
]
```

### findById($oTree, $id)

[](#findbyidotree-id)

Resursive search node in the all childs of the oTree (oNode). Each node will check as

```
$str = TreeAlgorithms::$idFieldName;
$node->$str == $id
```

Return null or founded node;

### remove($oTree, $id)

[](#removeotree-id)

Search node by id (see findById method), search parent node and remove node from parent node.

### getNodesByNodeId($oTree, $id)

[](#getnodesbynodeidotree-id)

Return array of nodes from tree root to node with id = id

Ru
==

[](#ru)

Что это
-------

[](#что-это)

Это группа методов для работы с древовидной структурой. Каждый элемент дерева должен иметь поля, такие как `id, parent_id, children`. Конкретные имена полей могут конфигурироваться перед запуском методов `TreeAlgorithms` путём изменения значений свойств `idFieldName, parentIdFieldName, childsFieldName`.

### getBranchIdList($node)

[](#getbranchidlistnode-1)

Рекурсивно обходит дерево и собирает идентификаторы элементов в один массив. В качестве идентификатора элмента используется его поле с именем, заданным в TreeAlgorithms.idFieldName. Идентификатор аргумента `$node` `id` из примера

```
	$sFieldName = static::$idFieldName;
	$id = $node->$sFieldName;
```

также будет содержаться в результате обхода, он будет в нулевой позиции массива.

### walkAndExecuteAction($oTree, $oCallback)

[](#walkandexecuteactionotree-ocallback-1)

Рекурсивно обходит дерево и для каждого элемента выполняет вызов колбэка. В колбэк передаётся элемент как аргумент.

oCallback должен быть объектом

```
//... in your class method body ...

$oCallback = new StdClass();
$oCallback->context = $this; //or static
$oCallback->f = 'yourClassMethodName';
$oCallback->isStatic = true; //or false if need static class
```

Вы можете не устанавливать поле isStatic если передаёте в контексте указатель на экземпляр класса.

### buildTreeFromFlatList($aScopeArgs, $bSetChildsAsArray = false)

[](#buildtreefromflatlistascopeargs-bsetchildsasarray--false-1)

Получает плоский список `Array` из `aScopeArgs` и строит из него дерево.

Например, aScopeArgs может быть таким:

```
$aFlatList = [
	[
		'id' => 1,
		'name' =>  'Books',
		'parent' => 0
	],
	[
		'id' => 2,
		'name' => 'Sciences',
		'parent' => 1
	],
	[
		'id' => 3,
		'name' => 'Adventure',
		'parent' => 1
	],
	[
		'id' => 4,
		'name' => 'Computer Sciences',
		'parent' => 2
	]
];
```

Тогда код:

```
TreeAlgorithms::$parentIdFieldName = 'parent';
TreeAlgorithms::$childsFieldName = 'inners';
$aTrees = TreeAlgorithms::buildTreeFromFlatList($aFlatList);
//$aTrees[0] will containt our tree
```

вернет массив:

```
[
	[
		'id' => 1,
		'name' => "Books",
		'parent' => 0,
		'inners' => {//(StdClass)
			'2' => [
				'id' => 2,
				'name' => 'Sciences',
				'parent' => 1,
				'inners' => {//(StdClass)
					'4' => [
						'id' => 4,
						'name' => 'Computer Sciences',
						'parent' => 2
					]
				}
			],
			'3' => [
				'id' => 3,
				'name' => 'Adventure',
				'parent' => 1
			]
		}
	]
]
```

Если вы передадите вторым аргументом истину `TreeAlgorithms.buildTreeFromFlatList(aFlatList, true)` результат будет:

```
[
	[
		'id' => 1,
		'name' => "Books",
		'parent' => 0,
		'inners' => [
			'2' => [
				'id' => 2,
				'name' => 'Sciences',
				'parent' => 1,
				'inners' => [
					'4' => [
						'id' => 4,
						'name' => 'Computer Sciences',
						'parent' => 2
					]
				]
			],
			'3' => [
				'id' => 3,
				'name' => 'Adventure',
				'parent' => 1
			]
		]
	]
]
```

### findById($oTree, $id)

[](#findbyidotree-id-1)

Рекурсивно обходит дерево и для каждого элемента сравнивает свойство, заданное в `TreeAlgorithms.idFieldName` с `id`. Если сравнение

```
$str = TreeAlgorithms::$idFieldName;
$node->$str == $id
```

оказалось истинным, вернёт найденный элемент, иначе null.

### remove($oTree, $id)

[](#removeotree-id-1)

Ищет элемент по id используя findById, если он найден ищет для него родительский элемент и удаляет из массива потомков найденный по id элемент.

### getNodesByNodeId($oTree, $id)

[](#getnodesbynodeidotree-id-1)

Возвращает массив объектов (элементов дерева) от корня до узла с id = id

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity28

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/0c515a68fa757958c4b37cf7c3083ad210d9be2a6059b7a255bd8c23856abfe0?d=identicon)[lamzin](/maintainers/lamzin)

---

Top Contributors

[![lamzin-andrey](https://avatars.githubusercontent.com/u/7406021?v=4)](https://github.com/lamzin-andrey "lamzin-andrey (14 commits)")

### Embed Badge

![Health badge](/badges/landlib-treealgorithms/health.svg)

```
[![Health](https://phpackages.com/badges/landlib-treealgorithms/health.svg)](https://phpackages.com/packages/landlib-treealgorithms)
```

###  Alternatives

[wikimedia/less.php

PHP port of the LESS processor

12327.4M77](/packages/wikimedia-lessphp)[trntv/probe

System information provider

33652.4k5](/packages/trntv-probe)[humanmade/wp-flags

Lightweight WordPress plugin to enable exposing feature flags to end-users, based on code-based ( or admin UI in the future ) criteria.

3553.5k](/packages/humanmade-wp-flags)[kanuni/filament-cards

519.0k](/packages/kanuni-filament-cards)[gggeek/ggsysinfo

Allows eZ Publish administrators and developers to have better insight into their working installation

137.8k](/packages/gggeek-ggsysinfo)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
