How can recursive queries be efficiently implemented in PHP for hierarchical data?

Recursive queries for hierarchical data in PHP can be efficiently implemented by using a recursive function that traverses the data structure, such as a tree or a nested array. The function should call itself recursively for each child element in the hierarchy until the desired depth is reached. This approach allows for flexible and dynamic handling of nested data structures.

function printHierarchy($data, $depth = 0) {
    foreach ($data as $item) {
        echo str_repeat("-", $depth) . $item['name'] . "\n";
        
        if (isset($item['children'])) {
            printHierarchy($item['children'], $depth + 1);
        }
    }
}

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

printHierarchy($data);