What are the best practices for handling group breaks and displaying data hierarchically in PHP?

When handling group breaks and displaying data hierarchically in PHP, it is important to properly structure the data and use loops to iterate through the groups. One common approach is to use nested loops to handle the hierarchy levels and display the data accordingly.

// Sample data array with hierarchical structure
$data = array(
    array('group' => 'A', 'name' => 'John'),
    array('group' => 'A', 'name' => 'Jane'),
    array('group' => 'B', 'name' => 'Bob'),
    array('group' => 'B', 'name' => 'Alice'),
);

// Sort data by group
usort($data, function($a, $b) {
    return $a['group'] <=> $b['group'];
});

$currentGroup = null;

foreach ($data as $item) {
    if ($item['group'] !== $currentGroup) {
        echo '<h2>' . $item['group'] . '</h2>';
        $currentGroup = $item['group'];
    }
    
    echo '<p>' . $item['name'] . '</p>';
}