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 and we hope to make good use of them.
One-dimensional array
Example
The code is as follows: |
Copy code |
<? Php Function my_sort ($ a, $ B) { If ($ a = $ B) return 0; Return ($ a> $ B )? -1: 1; } $ People = array ("Swanson" => "Joe ", "Griffin in" => "Peter", "Quagmire" => "Glenn ", "Swanson" => "joe", "griffin" => "peter ", "Quagmire" => "glenn "); Uksort ($ people, "my_sort "); Print_r ($ people ); ?> Output: Array ( [Swanson] => joe [Quagmire] => glenn [Griffin in] => peter [Swanson] => Joe [Quagmire] => Glenn [Griffin in] => Peter ) |
For example, if the following two-dimensional array needs to be sorted by the sort key name, then array_multisort () cannot be directly implemented:
The code is as follows: |
Copy code |
$ Data [5] = array ('Volume '=> 67, 'version' => 2 ); $ Data [4] = array ('Volume '=> 86, 'version' => 1 ); $ Data [2] = array ('Volume '=> 85, 'version' => 6 ); $ Data [3] = array ('Volume '=> 98, 'version' => 2 ); $ Data [1] = array ('Volume '=> 86, 'version' => 6 ); $ Data [6] = array ('Volume '=> 67, 'version' => 7 ); // Prepare the array to be sorted Foreach ($ data as $ k => $ v ){ $ Edition [] = $ v ['version']; } Array_multisort ($ edition, SORT_ASC, $ data ); Print_r ($ data); outputs: Array ( [0] => Array ( [Volume] => 86 [Edition] => 1 ) [1] => Array ( [Volume] => 67 [Edition] => 2 ) [2] => Array ( [Volume] => 98 [Edition] => 2 ) [3] => Array ( [Volume] => 85 [Edition] => 6 ) [4] => Array ( [Volume] => 86 [Edition] => 6 ) [5] => Array ( [Volume] => 67 [Edition] => 7 ) ) |
• 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.