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 ?>
  • 相关阅读:
    byte b=1、b=b+1、b+=1
    parameter ‘0’ not found
    Java设计模式—Singleton
    EL JSTL(得劲)
    天网恢恢Filter 窃听风云Listener
    Jsp学习总结(二)
    Jsp学习总结(一)
    Bugs(识破)
    [PAT乙级] Practise 1016 部分A+B
    [PAT乙级] Practise 1015 德才论
  • 原文地址:https://www.cnblogs.com/tinyphp/p/2724636.html
Copyright © 2011-2022 走看看