php 28 lines · 6 steps

Building a tree from a flat list in PHP

Group rows by parent once, then recurse to nest each node's children.

Explained by highlit
1<?php
2 
3function buildTree(array $items, ?int $parentId = null): array
4{
5 $indexed = [];
6 foreach ($items as $item) {
7 $indexed[$item['parent_id'] ?? 0][] = $item;
8 }
9 
10 return attachChildren($indexed, $parentId ?? 0);
11}
12 
13function attachChildren(array $indexed, int $parentId): array
14{
15 $branch = [];
16 
17 foreach ($indexed[$parentId] ?? [] as $item) {
18 $children = attachChildren($indexed, $item['id']);
19 
20 if ($children !== []) {
21 $item['children'] = $children;
22 }
23 
24 $branch[] = $item;
25 }
26 
27 return $branch;
28}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Indexing rows by parent once turns repeated O(n) scans into O(1) lookups per node.
  2. 2Recursion mirrors the tree's shape: each call handles one level and delegates the rest.
  3. 3Only attaching a children key when children exist keeps leaf nodes clean.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a tree from a flat list in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code