How can data be sorted and grouped effectively using PHP to improve output organization?
To sort and group data effectively in PHP, you can use the array_multisort() function to sort the data based on specific keys and criteria. You can also use the array_group_by() function to group the data based on a specific key or condition. These functions can help improve the organization and output of data in PHP.
// Sample data array
$data = [
['name' => 'John', 'age' => 30, 'city' => 'New York'],
['name' => 'Jane', 'age' => 25, 'city' => 'Los Angeles'],
['name' => 'Bob', 'age' => 35, 'city' => 'Chicago'],
['name' => 'Alice', 'age' => 28, 'city' => 'New York'],
];
// Sort data by age in ascending order
array_multisort(array_column($data, 'age'), SORT_ASC, $data);
// Group data by city
$groupedData = [];
foreach ($data as $item) {
$groupedData[$item['city']][] = $item;
}
// Output sorted and grouped data
print_r($groupedData);