开发者

Sort a 2d array with rows containing year, then month, then day values

I gener开发者_如何学运维ate an array with rearranged date values in it

$totert = [
    ['2011', '07', '25'],
    ['2011', '07', '27'],
    ['2011', '06', '25'],
    ['2011', '06', '02'],
    ['2011', '05', '25'],
    ['2011', '05', '15']
];

Expected result:

[
    ['2011', '05', '15'],
    ['2011', '05', '25'],
    ['2011', '06', '02'],
    ['2011', '06', '25'],
    ['2011', '07', '27'],
    ['2011', '07', '25']
]


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);


sort() is perfectly suited to order your rows of date values because each row has an equal length and your columns are arranged in a "big-endian" fashion.

Code: (Demo)

sort($totert);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜