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.
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 units by key names from low to high.
• The krsort () function is used to sort array units 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 will rank first no matter the size of $ B. check the program running result below:
The instance code is as follows:
- $ Ar1 = array ("ten", 100,100, "");
- $ Ar2 = array (1, 3, "2", 1 );
- Array_multisort ($ ar1, $ ar2 );
- Var_dump ($ ar1 );
- Var_dump ($ ar2 );
- ?>
Random Sorting
The instance code is as follows:
- $ 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
The code of the multi-dimensional array sorting instance is as follows:
- $ 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.