Home > Backend Development > PHP Tutorial > Examples of custom array sorting functions and sorting classes implemented in PHP

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

高洛峰
Release: 2023-03-03 13:46:02
Original
1378 people have browsed it

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;;
}
Copy after login

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;
   }
}
Copy after login


Related labels:
php
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template