ForThe Listing J example illustrates how the PHP function array_multisort () works:
- <?php
- $data = array(array("id" => 1, "name" => "Boney M", "rating" => 3),
- array("id" => 2, "name" => "Take That", "rating" => 1),
- array("id" => 3, "name" => "The Killers", "rating" => 4),
- array("id" => 4, "name" => "Lusain", "rating" => 3),
- ); foreach ($data as $key => $value) {
- $name[$key] = $value['name'];
- $rating[$key] = $value['rating'];
- }
- array_multisort($rating, $name, $data); print_r($data);
- ?>
Here, we simulate an array of rows and columns in the $ data array. Then, I use the PHP function array_multisort () to rearrange the data set. First, sort the data set by rating, and then sort the data by name if rating is equal. The output result is as follows:
Array ([0] => Array
(
[Id] => 2
[Name] => Take That
[Rating] => 1
) [1] => Array
(
[Id] => 1
[Name] => Boney M
[Rating] => 3
)
[2] => Array
(
[Id] => 4
[Name] => Lusain
[Rating] => 3
)
[3] => Array
(
[Id] => 3
[Name] => The Killers
[Rating] => 4
)
)
The PHP function array_multisort () is one of the most useful functions in PHP and has a wide range of applications. In addition, as you can see in the example, it can sort multiple irrelevant arrays, or use one of the elements as the basis for next sorting, you can also sort database result sets.