1

我在 php 中有这个数组之王,想按数组的日期 Array[i][2] 对其进行排序.. 最高日期应该在顶部.. 我该怎么做?

这是我的数组:

Array ( 
    [0] => Array ( 
        [0] => 15.04.2013 
        [1] => 17:34 
        [2] => 06.04.2013 
        ) 

    [1] => Array ( 
        [0] => 15.04.2013 
        [1] => 15:12 
        [2] => 13.04.2013 
    ) 

    [2] => Array ( 
        [0] => 15.04.2013 
        [1] => 16:42 
        [2] => 16.02.2013 
    ) 

    [3] => Array ( 
        [0] => 04.04.2013 
        [1] => 21:12 
        [2] => 16.03.2013 
    ) 

    [4] => Array ( 
        [0] => 29.04.2013 
        [1] => 17:16 
        [2] => 19.04.2013 
    ) 
) 
4

4 回答 4

2

您可以使用usort

例子:

usort($array,function ($a,$b){
    $t1 = strtotime($a[0]);
    $t2 = strtotime($b[0]);
    if ($t1 == $t2) {
        return 0;
    }
    return ($t1 < $t2) ? -1 : 1;
});
于 2013-04-29T17:36:59.100 回答
0

您可以使用 来执行此操作usort(),如下所示:

function cmp($a,$b) {
   if ($a[2] == $b[2]) {
      return 0;
   }
   $arr = explode('.',$a[2]);
   $brr = explode('.',$b[2]);
   $anum = (int) ($arr[2] . $arr[1] . $arr[0]);
   $bnum = (int) ($brr[2] . $brr[1] . $brr[0]);
   return ($anum < $bnum) ? -1 : 1;
}

usort($array, "cmp");
于 2013-04-29T17:43:59.330 回答
0

尝试这个:

function cmp($a, $b)
{
    $a = strtotime($a[2]);
    $b = strtotime($b[2]);
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array ( 
    0 => array ( 
        0 => '15.04.2013' 
        ,1 => '17:34'
        ,2 => '06.04.2013' 
        ) 

    ,1 => array ( 
        0 => '15.04.2013' 
        ,1 => '15:12' 
        ,2 => '13.04.2013' 
    ) 

    ,2 => array ( 
        0 => '15.04.2013' 
        ,1 => '16:42' 
        ,2 => '16.02.2013' 
    ) 

    ,3 => array ( 
        0 => '04.04.2013' 
        ,1 => '21:12' 
        ,2 => '16.03.2013' 
    ) 

) ;

usort($a, "cmp");
于 2013-04-29T17:44:55.910 回答
-1

you can write your custom sorter callback by using usort (like in lbu's answer)

array_multisort is the alternative, using like;

here is a sorter function for multi dimmensional arrays

https://gist.github.com/tufanbarisyildirim/1220785

于 2013-04-29T17:34:51.217 回答