1

I have this king of array in php and would like to sort it by the date Array[i][2] of the array.. the highest date should be at the top.. how can i do this?

this is my array:

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 
    ) 
) 
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125

4 Answers4

2

You can make use of usort

Example:

usort($array,function ($a,$b){
    $t1 = strtotime($a[0]);
    $t2 = strtotime($b[0]);
    if ($t1 == $t2) {
        return 0;
    }
    return ($t1 < $t2) ? -1 : 1;
});
Ibu
  • 42,752
  • 13
  • 76
  • 103
0

You can do it using usort() , like this:

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");
Nelson
  • 49,283
  • 8
  • 68
  • 81
0

Try this:

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");
Ali Seyfollahi
  • 2,662
  • 2
  • 21
  • 29
-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