How can recursive functions be implemented effectively in PHP to handle hierarchical data structures?

To effectively handle hierarchical data structures in PHP using recursive functions, you can create a function that calls itself within the function to traverse through the nested levels of the data structure. This allows you to process each level of the hierarchy without knowing the depth in advance.

function processHierarchy($data) {
    foreach ($data as $item) {
        if (is_array($item)) {
            processHierarchy($item); // recursively call the function for nested arrays
        } else {
            // process the item at this level
            echo $item . "\n";
        }
    }
}

$data = [
    'A',
    'B',
    ['C', 'D'],
    'E',
    ['F', ['G', 'H']]
];

processHierarchy($data);