This article mainly introduced the PHP implementation of the custom array sorting function and sorting class, combined with an example of PHP custom two-dimensional array sorting function and sorting class related implementation skills, the need for friends can refer to the next
In this paper, we describe the custom array sorting functions and sorting classes implemented by PHP. Share to everyone for your reference, as follows:
/** two-dimensional array custom sort 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 classes in the manual:
Class multisort{ var $key; The key in your array //Sort function parameter is the array to be sorted by the index sort type 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 order 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;< C27/>else if ($x [$this->key] > $y [$this->key]) return-1; else return 1;} }
The above is the whole content of this article, I hope that everyone's study has helped.