What are best practices for generating a hierarchical structure in PHP based on database fields like ID, parentID, name, level, and leaf?

When generating a hierarchical structure in PHP based on database fields like ID, parentID, name, level, and leaf, one common approach is to use a recursive function to build the tree structure. This function should iterate over the database records, grouping them by their parentID to form parent-child relationships. Additionally, the function should handle the level and leaf properties to accurately represent the hierarchy.

function buildHierarchy($items, $parentId = 0) {
    $hierarchy = array();
    
    foreach ($items as $item) {
        if ($item['parentID'] == $parentId) {
            $children = buildHierarchy($items, $item['ID']);
            if ($children) {
                $item['children'] = $children;
            }
            $hierarchy[] = $item;
        }
    }
    
    return $hierarchy;
}

// Assuming $records is an array of database records with fields ID, parentID, name, level, and leaf
$hierarchy = buildHierarchy($records);

// Use $hierarchy to display or manipulate the hierarchical structure