Oihana PHP Arango

buildTree.php

Table of Contents

Functions

buildTree()  : array<string|int, mixed>
Reconstructs a nested `children[]` tree from a **flat** list of nodes.

Functions

buildTree()

Reconstructs a nested `children[]` tree from a **flat** list of nodes.

buildTree(array<string|int, mixed> $flat[, string $parentSource = AQL::_PARENT ][, string|null $rootKey = null ][, string $childrenKey = AQL::CHILDREN ][, string $keyField = Schema::_KEY ]) : array<string|int, mixed>

The flat list is the shape produced by a depth-ranged edge projection (see buildEdgeVariable() with AQL::MAX_DEPTH): every element is an associative row that knows its parent — either through the AQL::WITH_PATH injected _parent key (default), or through a parent field the document already stores (pass its name as $parentSource, e.g. 'broader').

Each returned node gains a $childrenKey (default children) holding its direct children, recursively.

Roots

  • When $rootKey is given, the roots are the nodes whose parent equals it (the start vertex of the traversal — its own key). This is what buildTreeAlter() passes (the document's _key).
  • When $rootKey is null, a node is a root when its parent key is absent from the list (a depth-1 node points at the — unlisted — start vertex).

Robustness

The reconstruction is O(n) and cycle-safe: a node already seen on the current branch is never descended into again (pathological self-referential data cannot cause infinite recursion). A node whose parent is missing simply becomes a root. Each node is expected to have a single parent — with AQL::WITH_PATH this is guaranteed by the traversal's global vertex uniqueness. Rows that are not associative arrays are ignored.

Parameters
$flat : array<string|int, mixed>

The flat list of nodes (associative arrays).

$parentSource : string = AQL::_PARENT

The key holding each node's parent key (default AQL::_PARENT = _parent).

$rootKey : string|null = null

The start-vertex key; null infers the roots.

$childrenKey : string = AQL::CHILDREN

The key under which children are nested (default children).

$keyField : string = Schema::_KEY

The identity key of a node (default Schema::_KEY = _key).

Tags
example
$flat =
[
    [ '_key' => 'mammals' , '_parent' => 'animals' ] ,
    [ '_key' => 'dogs'    , '_parent' => 'mammals' ] ,
    [ '_key' => 'cats'    , '_parent' => 'mammals' ] ,
];
$tree = buildTree( $flat , rootKey: 'animals' ) ;
// [ [ '_key'=>'mammals', '_parent'=>'animals', 'children'=>[
//       [ '_key'=>'dogs', …, 'children'=>[] ], [ '_key'=>'cats', …, 'children'=>[] ] ] ] ]
author

Marc Alcaraz

since
1.5.0
Return values
array<string|int, mixed>

The list of root nodes, each with a nested $childrenKey.

On this page

Search results