Examples of custom array sorting functions and sorting classes implemented by PHP

Source: Internet
Author: User
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;}   }
  
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.