This article describes how to sort arrays by using functions provided by php, including one-dimensional array ranking, multi-dimensional array sorting, and random sorting.
Array_multisort ($ a, $ B), $ a, $ B is two numbers
• The sort () function is used to sort array units from low to high.
• Rsort () is used to sort array units from high to low.
• The asort () function is used to sort array units from low to high and maintain the index relationship.
• Arsort () is used to sort array units from high to low and maintain the index relationship.
• The ksort () function is used to sort array cells by key names from low to high.
• The krsort () function is used to sort array cells by key names from high to low.
Sort multiple arrays
Array_multisort ($ a, $ B), $ a, $ B are two arrays. After sorting, the 3rd elements in the $ a array are ranked first, then, the third element of $ B is ranked first regardless of its size in $ B. Check the program running result below:
| The Code is as follows: |
Copy code |
|
<? Php
$ Ar1 = array ("Ten", 100,100, "");
$ Ar2 = array (1, 3, "2", 1 );
Array_multisort ($ ar1, $ ar2 );
Var_dump ($ ar1 );
Var_dump ($ ar2 );
?> |
Random sorting
| The Code is as follows: |
Copy code |
|
$ Array = array ('A', '2', '3', '4', '5', '6', '7', '8 ', '9', '10', 'J', 'Q', 'k ');
Shuffle ($ array); // random sorting array
Print_r ($ array); // output array |
. Sort multi-dimensional arrays
| The Code is as follows: |
Copy code |
|
<? Php
$ Ar = array ("10", 100,100, "a"), array (1, 3, "2", 1 ));
Array_multisort ($ ar [0], SORT_ASC, SORT_STRING,
$ Ar [1], SORT_NUMERIC, SORT_DESC );
?> |
The most common function of array sorting is sort ($ arr). It is used to sort the key values of an array in ascending order, and the sorted array key name is no longer the original key name, is the key name reset by the new array.
Sometimes we need more complex sorting. For example, to sort key names, ksort ($ arr) is used here. It sorts the keys of the array and maintains the original key-value relationship. The corresponding asort ($ arr); function is used to sort key values and maintain the original key-value relationship.
In the same principle, rsort (); arsort (); krsort (); functions are sorted in descending order, and other functions include sort (); rsort (); ksort (); same.
Array operations are an important foundation for PHP.