PHP has a lot of built-in sorting functions, pros and cons of various rows;
Commonly used sorting functions:
Sort ()-sorts an array in ascending order
Rsort ()-sorts the array in descending order
Asort ()-sorts associative arrays in ascending order based on values
Ksort ()-Sorts the associative array in ascending order, based on the key
Arsort ()-sorts associative arrays in descending order by value
Krsort ()-Sorts the associative array in descending order, based on the key
Basic can meet the needs of the use of these functions are not more verbose;
But in the actual development of the project there will be some more demanding sorting requirements; the sort function to be introduced today is: Uasort ()
Uasort is mainly used in the order of the multidimensional arrays that need to follow the custom method and keep the index relationship;
Has the following array
$sort _array = Array (
"Array1" = = Array (
' word ' = ' test1 ',
' Sortnumber ' =>1,
),
' Array3 ' =>array (
' word ' = ' test4 ',
' Sortnumber ' =>4,
),
' Array2 ' =>array (
' word ' = ' test3 ',
' Sortnumber ' =>3,
),
' Array5 ' =>array (
' word ' = ' test5 ',
),
' Array4 ' =>array (
' word ' = ' test2 ',
' Sortnumber ' =>2,
),
);
The requirements are sorted in ascending order according to Sortnumber;
First, you need to write a custom sort rule;
Custom sort Functions
function My_sort ($a, $b) {
$prev = isset ($a [' sortnumber '])? $a [' Sortnumber ']: 0;
$next = Isset ($b [' Sortnumber '])? $b [' Sortnumber ']: 0;
if ($prev = = $next) return 0;
Return ($prev < $next)? -1:1;
}
Echo ' <pre> sort before:<br> ';
Print_r ($sort _array);
Uasort ($sort _array, "My_sort");
echo ":<br> after sorting";
Print_r ($sort _array);
The results obtained:
Before sorting:
Array
(
[Array1] = = Array
(
[Word] = Test1
[Sortnumber] = 1
)
[Array3] = = Array
(
[Word] = test4
[Sortnumber] = 4
)
[Array2] = = Array
(
[Word] = Test3
[Sortnumber] = 3
)
[Array5] = = Array
(
[Word] = Test5
)
[Array4] = = Array
(
[Word] = Test2
[Sortnumber] = 2
)
)
After sorting:
Array
(
[Array5] = = Array
(
[Word] = Test5
)
[Array1] = = Array
(
[Word] = Test1
[Sortnumber] = 1
)
[Array4] = = Array
(
[Word] = Test2
[Sortnumber] = 2
)
[Array2] = = Array
(
[Word] = Test3
[Sortnumber] = 3
)
[Array3] = = Array
(
[Word] = test4
[Sortnumber] = 4
)
)
The last to be reminded is: the custom function to use isset detection under the need to sort the existence of the field if there is no default 0 assigned to, otherwise there will be an error message;
PHP multidimensional Array custom sort Uasort ()