How can SQL queries be optimized in PHP when using nested sets for menu categories?

When using nested sets for menu categories in PHP, SQL queries can be optimized by using proper indexing on the nested set columns and minimizing the number of recursive queries. One way to optimize SQL queries is to use a single query to retrieve all menu categories and then construct the nested structure in PHP code.

// Assuming $pdo is the PDO object connected to the database

// Retrieve all menu categories with nested set columns
$stmt = $pdo->query("SELECT id, name, lft, rgt FROM menu_categories ORDER BY lft");

// Fetch all categories into an associative array
$menuCategories = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Build nested structure from the flat array
$menuTree = [];
foreach ($menuCategories as $category) {
    $node = &$menuTree;
    foreach (explode('.', $category['lft']) as $index) {
        $node = &$node[$index];
    }
    $node = $category;
}

// Now $menuTree contains the nested structure of menu categories