How can recursive functions or iterators be utilized in PHP to efficiently process and display nested category data retrieved from a database?

To efficiently process and display nested category data retrieved from a database in PHP, recursive functions or iterators can be utilized. By recursively iterating through the nested data structure, you can easily handle an unknown depth of categories and display them in a structured format on a webpage.

<?php
// Function to recursively process and display nested category data
function displayNestedCategories($categories, $parent_id = 0, $level = 0) {
    foreach ($categories as $category) {
        if ($category['parent_id'] == $parent_id) {
            echo str_repeat('-', $level) . $category['name'] . "<br>";
            displayNestedCategories($categories, $category['id'], $level + 1);
        }
    }
}

// Example usage
$categories = [
    ['id' => 1, 'parent_id' => 0, 'name' => 'Category 1'],
    ['id' => 2, 'parent_id' => 1, 'name' => 'Subcategory 1.1'],
    ['id' => 3, 'parent_id' => 1, 'name' => 'Subcategory 1.2'],
    ['id' => 4, 'parent_id' => 0, 'name' => 'Category 2'],
    ['id' => 5, 'parent_id' => 4, 'name' => 'Subcategory 2.1'],
];

displayNestedCategories($categories);
?>