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

Custom array sorting function and sorting class method implemented in PHP

墨辰丷
墨辰丷Original
2018-05-30 16:55:311561browse

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 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['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
   //排序函数 参数依次是 数组 待排列索引 排序类型
   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;
   }
   //正序
   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:

Detailed explanation of the method of storing/depositing PHPSession into redis

phpMethods to obtain parameters in cli mode

##phpMethods to improve efficiency by finding array elements


The above is the detailed content of Custom array sorting function and sorting class method 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