How can flexibility be maintained in PHP when dealing with varying depths of hierarchical data structures?

When dealing with varying depths of hierarchical data structures in PHP, one way to maintain flexibility is by using recursion to traverse the structure. By recursively iterating through the nested data, you can handle structures of any depth without needing to know the exact levels beforehand.

function processNestedData($data) {
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            processNestedData($value); // recursively call the function for nested arrays
        } else {
            // process the leaf node data here
            echo $key . ': ' . $value . PHP_EOL;
        }
    }
}

// Example usage
$data = [
    'name' => 'John Doe',
    'age' => 30,
    'children' => [
        'child1' => [
            'name' => 'Alice',
            'age' => 5
        ],
        'child2' => [
            'name' => 'Bob',
            'age' => 8
        ]
    ]
];

processNestedData($data);