How can recursive programming be utilized in PHP to handle hierarchical data?

When dealing with hierarchical data in PHP, recursive programming can be utilized to traverse and manipulate nested structures such as trees or directories. By using a recursive function, you can easily navigate through the levels of the hierarchy and perform operations on each node or element.

// Example of a recursive function to handle hierarchical data in PHP

function processNode($node) {
    // Perform operations on the current node
    echo $node['name'] . "\n";

    // Check if the node has children
    if(isset($node['children'])) {
        // Recursively process each child node
        foreach($node['children'] as $child) {
            processNode($child);
        }
    }
}

// Example hierarchical data structure
$data = [
    'name' => 'Parent',
    'children' => [
        [
            'name' => 'Child 1',
            'children' => []
        ],
        [
            'name' => 'Child 2',
            'children' => [
                [
                    'name' => 'Grandchild 1',
                    'children' => []
                ]
            ]
        ]
    ]
];

// Start processing the hierarchical data
processNode($data);