【问题标题】:Sort array in chronological order with date as key -php按时间顺序对数组进行排序,日期为键 -php
【发布时间】:2016-11-15 22:15:18
【问题描述】:

我基本上有这个代码来确定数组中相同日期的数量:

function get_archives_html ($blog) {
    //tag array to store arrays with same tag
    $count_tags = array();


    //store output
    $output = '';

    foreach($blog as $id) {
        //abbreviate date name
        $originalDate = $id["date"]["year"].'-'.$id["date"]["month"].'-'.$id["date"]["day"];
        $abbrevDate = date("F, Y", strtotime($originalDate));

        if(!isset($count_tags[$abbrevDate])) {
            $count_tags[$abbrevDate] = 0;
        }

        ++$count_tags[$abbrevDate];
    }

    // Sort your tags from hi to low
    //arsort($count_tags);
    var_dump($count_tags);




    foreach($count_tags as $month=>$id) {
        $output.= '<p><a href="#">'. $month.($id > 1 ? ' ('.$id .')' : '').'</a></p>';
    }

    return $output;
}

输出如下所示:

 $arr = array(
        "November, 2016" => "2",
        "October, 2016" => "5",
        "October, 2017" => "3",
        "September, 2017" => "6" 
    );

现在,我使用按键将其显示在 html 上。问题是它没有按日期正确排列,而是按字母排列。

所以,我的问题是,如何按键和日期对这个数组进行排序。例如 2016 年 10 月、2016 年 11 月、2017 年 9 月、2014 年 10 月 谢谢

【问题讨论】:

  • 您大概希望按时间顺序排列(即 16 年 10 月、16 年 11 月、17 年 9 月、17 年 10 月)?这个数组是从哪里来的?
  • 您的问题并未明确说明您的期望。排序键是ksort 为什么这样不行?
  • 您可能想查看uksort() 以使用数组的键定义自定义排序函数。另请注意,如果您有两次相同的日期,则将日期作为键可能不是一个好主意。
  • @Chris 这是正确的。它来自一个基本的多维数组。我在上面发布了整个代码
  • @Simon,嗨,它不起作用,因为我需要它按时间顺序排列,就像 chris states 一样。请参考上面的代码。谢谢

标签: php arrays sorting


【解决方案1】:
<?php
$arr = array(
        "November, 2016" => "2",
        "October, 2016" => "5",
        "October, 2017" => "3",
        "September, 2017" => "6" 
);

//Sort by ascending date in the key
uksort($arr,function($a,$b){
  return strtotime(strtr($a,',',' '))<=>strtotime(strtr($b,',',' '));
});

//result
$expected = array (
  'October, 2016' => "5",
  'November, 2016' => "2",
  'September, 2017' => "6",
  'October, 2017' => "3",
);

var_dump($arr === $expected);  //bool(true)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 2020-01-20
    • 2012-08-16
    • 2021-09-19
    相关资源
    最近更新 更多