【问题标题】:Sort an array on date按日期对数组进行排序
【发布时间】:2012-05-17 14:03:23
【问题描述】:

我知道可以找到很多关于按日期排序数组的帖子。我挣扎了好几个小时试图对我的('$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');

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

任何帮助将不胜感激!

【问题讨论】:

  • 什么不起作用,它是否返回任何错误,或者它只是不排序?
  • 你能改变你原来的$array(9)的结构吗?
  • 它只是不按日期排序。
  • 我同意@sebas,这不起作用,因为您的日期实际上不是数组中的键,它们是独立子数组中的键
  • @Sebas:我想保持原样......

标签: php date sorting


【解决方案1】:

在您的内部数组中,日期字符串实际上是数组键。所以你需要在键本身上调用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');

【讨论】:

  • 迈克尔,你拯救了我的一天!!我花了这么多时间,你在 3 分钟内解决了它!这是难以置信的。非常感谢!!!!
猜你喜欢
  • 2021-02-23
  • 2016-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-24
  • 2014-10-19
相关资源
最近更新 更多