How can arrays be effectively used in PHP to manipulate and sort data retrieved from a database?
When retrieving data from a database in PHP, it is common to store the results in an array for easier manipulation and sorting. By using PHP array functions such as `array_push`, `array_merge`, `usort`, and `array_multisort`, you can effectively manipulate and sort the data retrieved from a database.
// Assume $data is an array containing data retrieved from a database
// Sort the data by a specific key in ascending order
usort($data, function($a, $b) {
return $a['key'] <=> $b['key'];
});
// Sort the data by a specific key in descending order
usort($data, function($a, $b) {
return $b['key'] <=> $a['key'];
});
// Merge two arrays
$additionalData = array("key" => "value");
$data = array_merge($data, $additionalData);
// Push an element to the end of the array
$newElement = array("key" => "value");
array_push($data, $newElement);