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.
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.
$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.
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.
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.
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.