PHP hierarchical array - Parents and childs

PHP hierarchical array - Parents and childs

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

Stefan Bogdanescu

Founder & Senior Architect

Converting Flat Hierarchical Arrays into Nested Structures in PHP

Working with hierarchical data in PHP often comes down to a specific challenge: transforming a flat, adjacency-list style array into a nested tree structure. You might encounter this when processing JSON responses from an API or migrating data where parent-child relationships are stored as simple key-value pairs rather than explicit nesting. The goal is to take input like the example below and produce a readable, deeply nested array that reflects the full hierarchy.

$input = [
    33 => ['0' => '27', '1' => '41'],
    27 => ['0' => '64', '1' => '71'],
    0  => ['0' => '28', '1' => '29', '2' => '33'],
];

The desired output should look something like this:

$output = [
    0 => [
        '28',
        '29',
        33 => [
            '27' => [
                '64',
                '71'
            ],
            '41'
        ]
    ]
];

The core problem is determining the depth of each node without prior knowledge of the tree's maximum depth. A simple foreach loop over the top-level keys won't suffice because it cannot traverse into children to build their own sub-arrays. You need a mechanism that can process the root, then recursively handle its children.

Why Recursion Is Necessary

The most straightforward approach is a recursive function. This method mirrors the structure of the data itself: a node contains children, which are themselves nodes containing further children. The function accepts an ID, checks if that ID exists in the input array as a parent, and if so, iterates over its direct children. For each child, it calls the function again with that child's ID to build the next level of the tree.

Here is a basic implementation pattern:

function buildTree($id, $data) {
    if (!isset($data[$id])) {
        return null;
    }

    $children = [];
    
    foreach ($data[$id] as $childId) {
        // Determine what to put in the current level.
        // If the child is a leaf (has no children defined), just add the ID.
        // If it has children, recurse to build its subtree.
        
        $children[] = $childId;
    }

    return $children;
}

However, the logic above needs refinement to distinguish between leaf nodes and intermediate parents. A more robust pattern separates the immediate children from their own subtrees:

function flattenToTree($parentId, $data) {
    if (!isset($data[$parentId])) {
        return null;
    }

    $children = [];
    foreach ($data[$parentId] as $childId) {
        // Check if this child has its own children defined in the source array
        if (isset($data[$childId])) {
            $children[$childId] = flattenToTree($childId, $data);
        } else {
            // It's a leaf node; store just the ID or value as needed
            $children[] = $childId; 
        }
    }

    return $children;
}

Handling Mixed Arrays and Consistency

A critical detail in this specific problem is handling mixed arrays where some entries are indexed numerically (leaves) and others are associative (parents). When you recurse, you must ensure the result maintains consistency. If a parent node has multiple children, one of which is a leaf and another is a branch, the array should reflect that distinction clearly.

In the provided example, 33 has two children: 27 (a parent) and 41 (a leaf). The resulting structure must show 41 as a direct element while nesting 27 with its own subtree. This requires checking whether the child ID exists as a key in the original $data array before deciding to recurse or simply append the value.

Performance Considerations at Scale

While recursion is elegant and easy to implement, it can hit PHP's default stack limit if the tree is extremely deep. For most hierarchical data models, such as file systems or organizational charts, this is rarely an issue. However, if you are dealing with millions of nodes or a pathologically deep structure, consider using an iterative stack-based approach instead. This trades code complexity for safety against Fatal error: Allowed memory size exceeded or recursion limits.

If your data originates from a database query using Idiorm or Laravel Eloquent, it is often more efficient to join the parent and child tables directly in the SQL layer rather than fetching flat lists and reconstructing them in PHP. This reduces memory overhead and leverages the database engine's optimization for tree traversal.

Ultimately, the recursive pattern remains the standard solution for converting adjacency-list arrays into nested trees in PHP. It is readable, maintainable, and handles variable depths naturally without requiring complex state management.

Our network