How can PHP developers efficiently handle nested structures and hierarchies when designing and outputting complex HTML layouts?

When dealing with nested structures and hierarchies in PHP for complex HTML layouts, developers can efficiently handle this by using recursive functions to iterate through the nested data and generate the corresponding HTML output. This approach allows for flexibility in handling varying levels of nesting and ensures that the HTML layout accurately reflects the hierarchical structure of the data.

function generateNestedHTML($data) {
    $html = '<ul>';
    
    foreach ($data as $item) {
        $html .= '<li>' . $item['name'];
        
        if (isset($item['children'])) {
            $html .= generateNestedHTML($item['children']);
        }
        
        $html .= '</li>';
    }
    
    $html .= '</ul>';
    
    return $html;
}

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

echo generateNestedHTML($data);