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
go
package api func RegisterRoutes(r *gin.Engine, deps *Dependencies) { r.GET("/health", func(c *gin.Context) {
Layering route groups and middleware in Gin
routing
middleware
authentication
Intermediate
8 steps
typescript
export class PriorityQueue<T> { private heap: Array<{ value: T; priority: number }> = []; get size(): number {
Building a binary-heap priority queue in TypeScript
binary-heap
priority-queue
generics
Intermediate
9 steps
php
final class ConfigResolver { private array $merged;
Layered config merging in PHP
recursion
immutability
variadics
Intermediate
8 steps
php
<?php function uploadDocument(string $endpoint, string $filePath, array $meta): array {
Uploading a file with cURL in PHP
curl
file-upload
http
Intermediate
8 steps
php
<?php namespace App\Console\Commands;
Streaming CSV imports in Laravel
lazy-evaluation
generators
batch-processing
Intermediate
7 steps
php
<?php namespace App\Services;
Resilient HTTP retries with Laravel's client
http-client
retry-logic
error-handling
Intermediate
7 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.