What are some best practices for structuring PHP code to handle nested arrays for HTML output?
When dealing with nested arrays for HTML output in PHP, it is important to properly structure your code to handle the complexity of nested data structures. One best practice is to use recursive functions to iterate through the nested arrays and generate the HTML output accordingly. This approach helps to keep the code clean, maintainable, and scalable.
function generateNestedHTML($data) {
$html = '';
foreach ($data as $key => $value) {
if (is_array($value)) {
$html .= '<div class="nested">';
$html .= generateNestedHTML($value);
$html .= '</div>';
} else {
$html .= '<div>' . $key . ': ' . $value . '</div>';
}
}
return $html;
}
$data = [
'name' => 'John Doe',
'age' => 30,
'address' => [
'street' => '123 Main St',
'city' => 'New York'
]
];
echo generateNestedHTML($data);