Current Location: Home> Latest Articles> How to Create a Tree Structure in PHP: Nested Loops and Recursion Explained

How to Create a Tree Structure in PHP: Nested Loops and Recursion Explained

M66 2025-10-25

How to Create a Tree Structure in PHP

Tree structures are widely used in web and system development to display hierarchical data, such as category lists, permission systems, or organization charts. PHP offers flexible methods to build tree structures, mainly through two approaches: nested loops and recursion.

Method One: Creating a Tree Using Nested Loops

The nested loop method involves storing nodes and their relationships in an array, then iterating through it to build the HTML structure that represents the hierarchy.

Implementation Steps

  • Create an array that stores nodes and their parent-child relationships.
  • Assign each node a parent and child index.
  • Use nested loops to traverse the array and build the HTML tree based on those relationships.

Example Code

$nodes = [
    [
        'id' => 1,
        'parent_id' => null,
        'children' => [2, 3]
    ],
    [
        'id' => 2,
        'parent_id' => 1,
        'children' => []
    ],
    [
        'id' => 3,
        'parent_id' => 1,
        'children' => []
    ],
];

function createTree($nodes) {
    $tree = '<ul>';
    foreach ($nodes as $node) {
        $tree .= '<li>' . $node['id'];
        if (!empty($node['children'])) {
            $tree .= createTree($node['children']);
        }
        $tree .= '</li>';
    }
    $tree .= '</ul>';
    return $tree;
}

echo createTree($nodes);

The code above demonstrates how to use nested loops to generate a simple tree structure in HTML.

Method Two: Creating a Tree Using Recursion

Compared to nested loops, the recursive method is cleaner and more scalable, especially when working with deeply nested hierarchical data. By calling the same function recursively, you can easily generate multi-level structures.

Implementation Steps

  • Define a recursive function that generates HTML output based on node depth.
  • Iterate through each node and check for child nodes.
  • If child nodes exist, call the function again to process them.

Example Code

function createTree($nodes, $depth = 0) {
    $tree = '';
    foreach ($nodes as $node) {
        $tree .= '<li style="padding-left:' . $depth * 10 . 'px">' . $node['id'] . '</li>';
        if (!empty($node['children'])) {
            $tree .= createTree($node['children'], $depth + 1);
        }
    }
    return $tree;
}

$nodes = [
    [
        'id' => 1,
        'parent_id' => null,
        'children' => [2, 3]
    ],
    [
        'id' => 2,
        'parent_id' => 1,
        'children' => []
    ],
    [
        'id' => 3,
        'parent_id' => 1,
        'children' => []
    ],
];

echo createTree($nodes);

This recursive approach results in a cleaner structure and is easy to maintain or style on the frontend.

Conclusion

Both methods are effective for creating tree structures in PHP. The nested loop method works well for simpler hierarchies, while the recursive method is better suited for complex and deeply nested data. Choosing the right approach based on your project’s needs can greatly improve development efficiency and maintainability.