What are some best practices for organizing and retrieving hierarchical data in PHP, such as categories and subcategories?

When organizing hierarchical data in PHP, such as categories and subcategories, a common approach is to use a nested set model or a parent-child relationship. One way to efficiently retrieve hierarchical data is by using recursive functions to traverse the tree structure. Additionally, storing the data in a database table with columns for the category ID, name, and parent category ID can simplify the organization and retrieval process.

// Example of organizing and retrieving hierarchical data in PHP

// Define a function to recursively retrieve all subcategories of a given category
function getSubcategories($category_id, $categories) {
    $subcategories = [];
    foreach ($categories as $category) {
        if ($category['parent_id'] == $category_id) {
            $subcategories[] = $category;
            $subcategories = array_merge($subcategories, getSubcategories($category['id'], $categories));
        }
    }
    return $subcategories;
}

// Example usage
$categories = [
    ['id' => 1, 'name' => 'Category 1', 'parent_id' => null],
    ['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' => null],
    ['id' => 5, 'name' => 'Subcategory 2.1', 'parent_id' => 4],
];

$subcategory_tree = getSubcategories(1, $categories);
print_r($subcategory_tree);