PHP-based custom array sorting function and sorting class example this article describes the PHP-based custom array sorting function and sorting class. 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'].'
';}
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 ;}}