How to sort a date array in PHP

大兔子大兔子 提交于 2019-11-26 16:20:47

Use the ISO (yyyy-mm-dd) format rather than the "english" format, and then just use the ksort function to get them in the right order.

There's no need to remove the hyphens, ksort will do an alphanumeric comparison on the string keys, and the yyyy-mm-dd format works perfectly well as the lexical order is the same as the actual date order.

EDIT I see you've now corrected your question to show that you've actually got an array of arrays, and that the sort key is in the sub-arrays. In this case, you should use uksort as recommended elsewhere, but I would recommend that you go with your own edit and sort based on the DB formatted date, rather than by parsing the human readable format:

function cmp($a, $b)
{
    global $array;
    return strcmp($array[$a]['db'], $array[$b]['db']);
}

uksort($array, 'cmp');

Actually, use this:

usort($array, "cmp");

function cmp($a, $b){ 
    return strcmp($b['db'], $a['db']); 
}

:)

Alexander
function cmp($a, $b) {    
    global $array;    
    return strcmp($array[$a]['db'], $array[$b]['db']); 
}    
uksort($array, 'cmp');

I think there is better to use usort() function instead of uksort(), because sometimes you can`t use global variables at all and anyway using global variables is not a good practice either.

You could also use anonymous function.

// Sort in chronological order.
usort($array, function($a, $b) {
  return strcmp($a['db'], $b['db']);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!