When we are learning PHP, we may be confused about the multi-dimensional array sorting of PHP. The article will introduce the principle of multi-dimensional array sorting of PHP in detail here. PHP also allows you to perform complex sorting on multi-dimensional arrays. For example, you can first sort a nested array by a common keyword and then sort it by another keyword. This is very similar to sorting multiple fields using the SQL ORDER BY statement. To better understand how it works, take a closer look at the example:
- <?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);?>
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. These examples should give you a preliminary understanding of the use of the PHP multi-dimensional array sorting function, and show you some internal functions hidden in the PHP Array Processing toolkit. Here, we simulate an array of rows and columns in the $ data array. Then, I use the array_multisort () function 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
- )
- )