What is the best way to structure and organize data output in PHP to display categories and subcategories?

When displaying categories and subcategories in PHP, the best way to structure and organize the data output is to use a recursive function. This function will loop through the categories and subcategories, checking for subcategories within each category, and outputting them accordingly.

function displayCategories($categories, $parent_id = 0, $level = 0) {
    foreach ($categories as $category) {
        if ($category['parent_id'] == $parent_id) {
            echo str_repeat('-', $level) . $category['name'] . "<br>";
            displayCategories($categories, $category['id'], $level + 1);
        }
    }
}

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

displayCategories($categories);