What are some best practices for querying and processing hierarchical data structures in PHP?

When querying and processing hierarchical data structures in PHP, it is important to use recursive functions to traverse the tree-like structure efficiently. This allows you to navigate through parent-child relationships and perform operations on each node as needed. Additionally, storing hierarchical data in a database using nested set or adjacency list models can simplify querying and manipulation of the data.

// Example of a recursive function to process hierarchical data
function processNode($node) {
    // Process current node
    echo $node['name'] . "\n";
    
    // Process child nodes recursively
    if(isset($node['children'])) {
        foreach($node['children'] as $child) {
            processNode($child);
        }
    }
}

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

// Process the hierarchical data
processNode($data);