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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Indexing rows by parent once turns repeated O(n) scans into O(1) lookups per node.
- 2Recursion mirrors the tree's shape: each call handles one level and delegates the rest.
- 3Only attaching a children key when children exist keeps leaf nodes clean.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-tree-from-a-flat-list-in-php-explained-php-f40a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.