在日期排序数组

时间:2012-05-17 14:03:24

标签: php date sorting

我知道可以在日期排序数组上找到很多帖子。我正在努力尝试排序我的('$ MyArray')没有任何成功(我是PHP的新手,所以如果答案很明显,请原谅我):

array(9) { 

    [0]=> array(1) {["13 March 2012"]=> string(32) "Commandes Anticorps et Kits 2012" }

    [1]=> array(1) {["4 May 2012"]=> string(23) "Prix de la Chancellerie" } 

    [2]=> array(1) { ["17 April 2012"]=> string(23) "MàJ antivirus Kapersky" }

    [3]=> array(1) { ["14 May 2012"]=> string(24) "Atelier Formation INSERM" }

    [4]=> array(1) { ["14 March 2012"]=> string(13) "Webzine AP-HP" }

    [5]=> array(1) { ["11 April 2011"]=> string(32) "Nouvelle Charte des Publications" }

    [6]=> array(1) { ["23 April 2012"]=> string(28) "BiblioINSERM: Nouveaux Codes" }

    [7]=> array(1) { ["7 March 2012"]=> string(39) "Springer : Protocols également en test" }

    [8]=> array(1) { ["4 October 2011"]=> string(48) "[info.biblioinserm] Archives des titres Springer" } 

    }

所以我想对日期进行排序。

在我找到的各种解决方案中,我尝试过:

function date_compare($a, $b)
{
    $t1 = strtotime($a['datetime']);
    $t2 = strtotime($b['datetime']);

return $t1 - $t2;
}

然后调用函数:

usort($MyArray, 'date_compare');

但它不起作用......: - (

任何帮助都将不胜感激!!

1 个答案:

答案 0 :(得分:2)

在内部数组中,日期字符串实际上是数组键。因此,您需要在密钥本身上调用strtotime()。这使用array_keys()从两个比较数组中提取键,并使用array_shift()来检索第一个(尽管只有一个)。

function date_compare($a, $b)
{
    // Remove the first array key (though there should be only one)
    // from both the $a and $b values:
    $akeys = array_keys($a);
    $akey = array_shift($akeys);
    // Could also use
    // $akey = akeys[0];

    $bkeys = array_keys($b);
    $bkey = array_shift($bkeys);
    // Could also use
    // $bkey = bkeys[0];

    // And call strtotime() on the key date values
    $t1 = strtotime($akey);
    $t2 = strtotime($bkey);

    return $t1 - $t2;
}

usort($MyArray, 'date_compare');
相关问题