ArrayTree

Rows into a Tree

ArrayTree::fromRows($items, $parentField, $childrenField, $parentId = null) uses the array keys as node identifiers. Each row’s parent field refers to the key of its parent.

use Derafu\Array\ArrayTree;

$items = [
    1 => ['parent_id' => null, 'name' => 'root'],
    2 => ['parent_id' => 1, 'name' => 'child'],
    3 => ['parent_id' => 2, 'name' => 'leaf'],
];

$tree = ArrayTree::fromRows($items, 'parent_id', 'children');
// [1 => ['name' => 'root', 'children' => [
//     2 => ['name' => 'child', 'children' => [
//         3 => ['name' => 'leaf', 'children' => []],
//     ]],
// ]]]

Keys are preserved, parent fields are removed, and the children field is present even when empty. Parent comparisons are strict: integer 1 and string '1' are different parent values.

Rows without the parent field, and branches not reachable from the selected root parent, are omitted. Supply rows keyed by their identifiers; for database lists, array_column($rows, null, 'id') can prepare that structure.

Tree into an Outline

toOutline($tree, $nameField, $childrenField) traverses depth first and returns each node’s name and nesting level, keeping its key:

ArrayTree::toOutline($tree, 'name', 'children');
// [
//     1 => ['name' => 'root', 'level' => 0],
//     2 => ['name' => 'child', 'level' => 1],
//     3 => ['name' => 'leaf', 'level' => 2],
// ]

This is an outline, not a reconstruction of the original rows: other fields are not included. Node keys must be unique across the tree to avoid later nodes replacing earlier outline entries.

A non-array node or a node with a missing or null name is skipped with its descendants. A node whose children field is not an array is included, but those children are omitted. The optional $level and by-reference $result parameters support recursive accumulation; ordinary callers use the first three arguments.

On this page

Last updated on 26/10/2026 by Anonymous