What are some examples of implementing nested sets in PHP for category organization?

Nested sets are a way to represent hierarchical data like category trees in a database table. One common way to implement nested sets in PHP is to use a recursive function to build the tree structure from the database records. This involves querying the database for all categories, then recursively building the tree structure by adding child categories to their parent categories.

// Function to fetch categories from the database
function fetchCategories($parent_id = 0) {
    $categories = [];
    
    // Query database for categories with parent_id
    $results = query("SELECT * FROM categories WHERE parent_id = $parent_id");
    
    foreach ($results as $result) {
        $category = [
            'id' => $result['id'],
            'name' => $result['name'],
            'children' => fetchCategories($result['id']) // Recursively fetch child categories
        ];
        
        $categories[] = $category;
    }
    
    return $categories;
}

// Usage example
$categories = fetchCategories();

// Print out the nested category structure
function printCategories($categories, $indent = 0) {
    foreach ($categories as $category) {
        echo str_repeat('-', $indent) . $category['name'] . PHP_EOL;
        
        if (!empty($category['children'])) {
            printCategories($category['children'], $indent + 2);
        }
    }
}

printCategories($categories);