Home  >  Article  >  Backend Development  >  Custom array sorting function and sorting class implemented in PHP

Custom array sorting function and sorting class implemented in PHP

墨辰丷
墨辰丷Original
2018-05-30 16:30:292285browse

This article mainly introduces the custom array sorting function and sorting class implemented in PHP, and analyzes the related implementation skills of PHP's custom two-dimensional array sorting function and sorting class in the form of examples. Friends in need can refer to the following

The example in this article describes the custom array sorting function and sorting class implemented in PHP. Share it with everyone for your reference, the details are as follows:

/*
* 二维数组自定义排序函数
* uasort($arr,function_name)
*
**/
$arr = array(
  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[&#39;b&#39;]<$y[&#39;b&#39;]){
    return -1;
  }else if($x[&#39;b&#39;]>$y[&#39;b&#39;]){
    return 1;
  }else{
    return 0;
  }
}
uasort($arr,&#39;compare_arr&#39;);
foreach($arr as $a){
  echo $a[&#39;a&#39;].&#39;=>&#39;.$a[&#39;b&#39;].&#39;<br/>&#39;;
}

Custom sorting class in the manual:

class multiSort
{
   var $key;  //key in your array
   //排序函数 参数依次是 数组 待排列索引 排序类型
   function run ($myarray, $key_to_sort, $type_of_sort = &#39;&#39;)
   {
     $this->key = $key_to_sort;
     if ($type_of_sort == &#39;desc&#39;)
       uasort($myarray, array($this, &#39;myreverse_compare&#39;));
     else
       uasort($myarray, array($this, &#39;mycompare&#39;));
     return $myarray;
   }
   //正序
   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;
   }
   //逆序
   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;
   }
}

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

How to implement proportional scaling and logo watermark functions of images in PHP

PHP implements the method of calling Mailgun to send emails

PHP jQuery implements the scrolling method of dynamically loading data without refreshing

The above is the detailed content of Custom array sorting function and sorting class implemented in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn