PHP-implemented custom array sorting function and sorting class example, array example
This article describes the PHP-implemented custom array sorting functions and sorting classes. We will share this with you for your reference. The details are as follows:
/** Two-dimensional array custom sorting function * uasort ($ arr, function_name) ***/$ arr = array ('A' => 1, 'B' => 'C'), array ('A' => 4, 'B' => 'A'), array ('A' => 5, 'B' => 'G'), array ('A' => 7, 'B' => 'F'), array ('A' => 6, 'B' => 'E'); function compare_arr ($ x, $ y) {if ($ x ['B'] <$ y ['B']) {return-1;} else if ($ x ['B']> $ y ['B']) {return 1 ;}else {return 0 ;}} uasort ($ arr, 'compare _ arr'); foreach ($ arr as $ a) {echo $ a ['a']. '=> '. $ a ['B']. '<br/> ';}
Custom sorting class in the manual:
Class multiSort {var $ key; // key in your array // The sorting function parameters are sorted by the array index in sequence. function run ($ myarray, $ key_to_sort, $ type_of_sort = '') {$ this-> key = $ key_to_sort; if ($ type_of_sort = 'desc') uasort ($ myarray, array ($ this, 'myreverse _ compare'); else uasort ($ myarray, array ($ this, 'mycompare'); return $ myarray;} // Positive Sequence function mycompare ($ x, $ y) {if ($ x [$ this-> key] =$ y [$ this-> key]) return 0; else if ($ x [$ this-> key] <$ y [$ this-> key]) return-1; else return 1 ;} // reverse function myreverse_compare ($ x, $ y) {if ($ x [$ this-> key] = $ y [$ this-> key]) return 0; else if ($ x [$ this-> key]> $ y [$ this-> key]) return-1; else return 1 ;}}