How can PHP developers handle data grouping and display based on specific criteria like departments or locations?
To handle data grouping and display based on specific criteria like departments or locations, PHP developers can use arrays to organize the data and then loop through the array to display the information based on the specified criteria.
// Sample data array
$data = [
['name' => 'John Doe', 'department' => 'HR', 'location' => 'New York'],
['name' => 'Jane Smith', 'department' => 'IT', 'location' => 'San Francisco'],
['name' => 'Alice Johnson', 'department' => 'HR', 'location' => 'New York'],
['name' => 'Bob Brown', 'department' => 'IT', 'location' => 'San Francisco'],
];
// Group data by department
$groupedData = [];
foreach ($data as $item) {
$groupedData[$item['department']][] = $item;
}
// Display data based on department
foreach ($groupedData as $department => $employees) {
echo "<h2>$department</h2>";
foreach ($employees as $employee) {
echo $employee['name'] . ' - ' . $employee['location'] . '<br>';
}
}