如何使用日期值对数组进行排序

I generate an array with rearranged date values in it

$totert = array(
    array('2011','07','25'),
    array('2011','07','27'),
    array('2011','06','25'),
    array('2011','06','02'),
    array('2011','05','25'),
    array('2011','05','15')
);

how to arrange the value based on date i mean

  • 2011-05-15
  • 2011-05-25
  • 2011-06-02
  • 2011-06-25
  • 2011-07-25
  • 2011-07-27

could someone help me

Use usort() and provide a custom comparison function.

$totert = array(
    array('2011','07','25'), 
    array('2011','07','27'), 
    array('2011','06','25'), 
    array('2011','06','02'), 
    array('2011','05','25'), 
    array('2011','05','15')
);
usort($totert, function($a, $b) {
    return (int)implode('', $a) - (int)implode('', $b);
});

print_r(array_map(function($v) {
    return implode('-', $v);
}, $totert));
$timestamps = array_map (function ($date) {
  return mktime(0,0,0, $date[1], $date[2], $date[0]);
}, $totert;

sort($timestamps);

The values are now UNIX-timestamps, buts ith date() its very easy to create any format you like again.

Another solution is to use simple string comparison

$dates = array_map (function ($date) {
  return implode('-', $date);
}, $totert;

sort($dates, SORT_STRING);

You can split (explode()) the single values at - again, if you really need the dates as an array.

    $totert = array(  
 array('2011','07','25'), 
 array('2011','07','27'), 
 array('2011','06','25'), 
 array('2011','06','02'), 
 array('2011','05','25'), 
 array('2011','05','15'));

function convert_to_date(&$item, $key)
{
    $item = $item[0].'-'.$item[1].'-'.$item[2];
}

array_walk($totert, 'convert_to_date');
sort($totert);
print_r($totert);