How can PHP's array_walk_recursive() function be used effectively in generating hierarchical structures?

When working with arrays in PHP, it can be challenging to generate hierarchical structures, especially if the array is multidimensional. PHP's array_walk_recursive() function can be used effectively to iterate through each element of the array, including nested arrays, and perform a callback function on each element. By using array_walk_recursive(), you can easily manipulate the array elements and build hierarchical structures based on your requirements.

// Sample multidimensional array
$data = [
    'name' => 'John',
    'age' => 30,
    'children' => [
        [
            'name' => 'Alice',
            'age' => 10
        ],
        [
            'name' => 'Bob',
            'age' => 8
        ]
    ]
];

// Function to append 'years' to the 'age' key
function appendYears(&$value, $key) {
    if ($key == 'age') {
        $value .= ' years';
    }
}

// Using array_walk_recursive to append 'years' to each 'age' value
array_walk_recursive($data, 'appendYears');

// Print the modified array
print_r($data);