2012-05-17 32 views
1

我知道可以在日期排序数组上找到许多帖子。我挣扎了几个小时尝试没有成功排序矿(“$ 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'); 

,但它不工作... :-(

任何帮助将非常感激!

+0

什么不行,它是否返回任何错误,或者它只是不排序? –

+0

你可以改变原来的$ array(9)的结构吗? – Sebas

+0

它只是不排序日期。 – user1401141

回答

2

在你内心的数组,日期字符串ACTUA lly数组键。所以你需要在键上自己拨打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'); 
+1

迈克尔,你救了我的一天!我花了这么多时间,你在3分钟内解决了它!这是令人难以置信的。非常感谢!!!! – user1401141