How can a recursive loop be used to create a tree structure output in PHP?

To create a tree structure output using a recursive loop in PHP, you can define a recursive function that traverses through the tree data structure and outputs the nodes accordingly. Each node can have children nodes, which are recursively processed by the function. This approach allows for a flexible and scalable way to represent hierarchical data structures.

// Define a recursive function to output tree structure
function printTree($node, $depth = 0) {
    if ($node) {
        echo str_repeat("-", $depth) . $node['name'] . PHP_EOL;
        if (!empty($node['children'])) {
            foreach ($node['children'] as $child) {
                printTree($child, $depth + 1);
            }
        }
    }
}

// Sample tree data structure
$tree = [
    'name' => 'Root',
    'children' => [
        [
            'name' => 'Child 1',
            'children' => [
                [
                    'name' => 'Grandchild 1',
                    'children' => []
                ]
            ]
        ],
        [
            'name' => 'Child 2',
            'children' => []
        ]
    ]
];

// Output the tree structure
printTree($tree);