PHP - How to build tree structure list?

PHP - How to build tree structure list?

  1. Blog
  2. 15 November 2026
  3. 5 min read

Stefan Bogdanescu

Founder & Senior Architect

Building a Tree Structure List in PHP

You have two tables: one representing parent nodes (pr_id, parent_name) and another representing children linked to those parents (ch_id, pr_id, child_name). The goal is to transform this flat, normalized data into a nested array or object structure that mirrors the hierarchy shown in your example. While the concept of recursion immediately comes to mind, simply writing a recursive function without a solid strategy for population order often leads to performance bottlenecks or infinite loops if not handled carefully.

The core challenge here is ordering. If you attempt to build the tree by starting at the root and recursively fetching children, you risk triggering thousands of database queries (the N+1 problem). A more robust approach involves aggregating the data first so that every node knows its immediate children are already loaded in memory. This allows you to construct the hierarchy using simple array manipulation rather than repeated I/O operations.

Aggregating Data by Parent ID

The most efficient pattern for this specific schema is a two-step process: fetch all records into memory, then group them. In your parent table, every row effectively represents a node in the tree, regardless of whether it appears as a "parent" or a "child" in the relational sense. The ch_id column acts as a child identifier, but logically, you want to treat every row in both tables as part of a single logical dataset where each row is a potential node.

First, retrieve all rows from your database. Assuming your tables are named parents and children, or perhaps they represent different views of the same entity, let's assume for this example that we have a unified view or we are querying both and merging them. If you strictly follow your schema where pr_id links to itself in the child table, you can execute a query that fetches all nodes with their immediate children counts.

// Fetch all nodes from the parent table (acting as roots) and the child table
$allNodes = [...]; // Result of your DB query fetching both tables or a union

// Group children by their parent_id ($pr_id in child table maps to pr_id in parent table)
$childrenByParent = [];
foreach ($allNodes as $node) {
    // Identify if this node is a root (exists only in parent table) or has children
    // For simplicity, assume we treat every row found in the union as a node.
    // We need to group the 'child' records under their corresponding 'parent' IDs.
    
    $id = $node['pr_id'];
    $childrenByParent[$id] = [];
}

// Iterate through child table specifically to attach children
foreach ($childTableRows as $row) {
    $parentId = $row['pr_id'];
    $childId = $row['ch_id'];
    
    if (!isset($childrenByParent[$parentId])) {
        $childrenByParent[$parentId] = [];
    }
    
    // Create a child object/array
    $childNode = [
        'id' => $childId,
        'name' => $row['child_name'],
        'children' => [] 
    ];
    
    $childrenByParent[$parentId][] = $childNode;
}

Constructing the Recursive Structure

Once you have a map of which parents have which children in memory (stored in $childrenByParent), building the actual tree becomes a straightforward recursive function. You iterate through your list of root nodes (those that appear in the parent table but not as a child, or simply by iterating the top level).

The recursion depth is determined by how many levels deep your data goes. In your example, p_0_1 has children p_0_1_0 and p_0_1_1, which have no further children listed, so the recursion stops there naturally when a node has an empty children array.

function buildTree($parentId, &$childrenMap) {
    if (!isset($childrenMap[$parentId])) {
        // If no children exist for this ID, return null or an empty array depending on needs
        return []; 
    }

    $treeItem = [
        'id' => $parentId,
        'name' => /* fetch name from parent table here */,
        'children' => []
    ];

    foreach ($childrenMap[$parentId] as $child) {
        // Recursively call for each child
        $childrenMap[$child['id']] = []; // Reset children map for the next level to avoid conflicts if not using a global ref correctly
        $treeItem['children'][] = buildTree($child['id'], $childrenMap);
    }

    return $treeItem;
}

// Usage: Start with root IDs (IDs that exist in parent table but are not referenced as ch_id)
$rootIds = [1, 4]; // Based on your sample data where 2 and 3 are intermediate nodes
foreach ($rootIds as $id) {
    $tree = buildTree($id, $childrenByParent);
}

Performance and Pitfalls

A common mistake when implementing this logic is failing to pre-aggregate the child data. If your recursive function queries the database inside the loop to find children for a specific parent, you will see exponential growth in query time as the tree depth increases. By loading all necessary relationships into memory first ($childrenByParent), you ensure that the recursion operates entirely on array lookups, which is O(1) complexity per step.

Another consideration is handling cycles. While your schema implies a strict parent-child hierarchy (DAG or Tree), real-world data can sometimes contain circular references if pr_id in the child table points back to a descendant. Always ensure your data integrity constraints prevent a node from being its own ancestor before attempting to build the tree.

For complex applications requiring frequent tree updates, consider caching the aggregated structure or using database-specific features like recursive CTEs (Common Table Expressions) if you are on a modern MySQL or PostgreSQL instance. However, for PHP-centric logic where you control the application flow, pre-aggregation remains the most portable and performant strategy.

If you need further assistance with Laravel-specific implementations or optimizing database queries for hierarchical data, check out resources like https://laravelcompany.com which often covers advanced Eloquent patterns.

Our network