zoukankan      html  css  js  c++  java
  • 二维数组按照某一键值进行排序

     1 <?
     2 $arr=array(array('id'=>'1','name'=>'lily','start'=>'20110101','end'=>'20110103'),
     3 array('id'=>'2','name'=>'may','start'=>'20110101','end'=>'20110105'));
     4 
     5 
     6 class array_sorter
     7 {
     8    var $skey = false;
     9    var $sarray = false;
    10    var $sasc = true;
    11 
    12    function array_sorter(&$array, $key, $asc=true)
    13    {
    14        $this->sarray = $array;
    15        $this->skey = $key;
    16        $this->sasc = $asc;
    17    }
    18 
    19    function sortit($remap=true)
    20    {
    21        $array = &$this->sarray;
    22        uksort($array, array($this, "_as_cmp"));
    23        if ($remap)
    24        {
    25            $tmp = array();
    26            while (list($id, $data) = each($array))
    27                $tmp[] = $data;
    28            return $tmp;
    29        }
    30        return $array;
    31    }
    32    function _as_cmp($a, $b)
    33    {
    34        if (!is_array($a) && !is_array($b))
    35        {
    36            $a = $this->sarray[$a][$this->skey];
    37            $b = $this->sarray[$b][$this->skey];
    38        }
    39 
    40        //if string - use string comparision
    41        if (!ctype_digit($a) && !ctype_digit($b))
    42        {
    43            if ($this->sasc)
    44                return strcasecmp($a, $b);
    45            else 
    46                return strcasecmp($b, $a);
    47        }
    48        else
    49        {
    50            if (intval($a) == intval($b)) 
    51                return 0;
    52 
    53            if ($this->sasc)
    54                return (intval($a) > intval($b)) ? -1 : 1;
    55            else
    56                return (intval($a) > intval($b)) ? 1 : -1;
    57        }
    58    }
    59 
    60 }
    61 
    62 function multi_sort(&$array, $key, $asc=true)
    63 {
    64        $sorter = new array_sorter($array, $key, $asc);
    65        return $sorter->sortit();
    66 }
    67    //false和true控制升降序,end为数组键值
    68 $my_array = multi_sort($arr, "end", false);
    69 print_r($my_array);
    70 
    71 
    72 ?>
  • 相关阅读:
    处理了一个“服务器能ping得通,但telnet连接失败”导致数据库登录不了的问题
    解决了一个oracle登录缓慢的问题
    今天解决了一个mysql远程登录和本机ip登录都失败的问题
    c++笔记
    c语言笔记
    常见并发与系统设计
    linux网络IO笔记
    linux文件IO全景解析
    linux网络协议笔记
    长大后才懂的蜡笔小新 ​​​​
  • 原文地址:https://www.cnblogs.com/tinyphp/p/2724636.html
Copyright © 2011-2022 走看看