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 namespace App\Models\Concerns;
Building soft deletes as an Eloquent trait in Laravel
traits
soft-delete
global-scope
Intermediate
10 steps
php
<?php namespace App\Services;
Idempotent role assignment in Laravel
many-to-many
pivot-data
idempotency
Intermediate
8 steps
php
<?php namespace App\Services;
Merging overlapping busy time blocks in PHP
interval-merging
sorting
datetime
Intermediate
8 steps
php
<?php namespace App\Listeners;
How event subscribers group listeners in Laravel
event-driven
subscribers
queues
Intermediate
6 steps
php
<?php namespace App\Services;
How user impersonation works in Laravel
authentication
authorization
session
Intermediate
8 steps
php
class OrderReceiptController extends Controller { public function store(Request $request, Order $order) {
Handling receipt uploads in a Laravel controller
file-upload
validation
authorization
Intermediate
5 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.