【问题标题】:Sorting a list of dates into an array of unique years/months/days将日期列表排序为唯一的年/月/日数组
【发布时间】:2020-01-21 18:49:56
【问题描述】:

我已经为此苦苦挣扎了一段时间,所以我决定寻求帮助。

我需要像这样转换日期列表:

2019-09-17,
2019-09-16,
2018-08-15,
2017-08-14

并将它们输出为唯一年/月/日的嵌套列表:

  • 2019
    • 09
      • 17
      • 16
  • 2018
    • 08
      • 15
  • 2017
    • 08
      • 14
$dates = wp_list_pluck( $queriedFiles->posts, 'post_date' );

$cleanDates = array();

foreach ($dates as $date) {
    $createDate = new DateTime($date);
    $date = $createDate->format('Y-m-d');
    array_push($cleanDates, $date);
}
$uniqueDates = array_unique($cleanDates);

$years = array();

$properDates = array();
foreach ($uniqueDates as $date) {
    $createDate = new DateTime($date);
    $strippedYear = $createDate->format('Y');
    $strippedMonth = $createDate->format('m');
    $strippedDay = $createDate->format('d');

    $thisDate = array('year' => $strippedYear, 'month'=>$strippedMonth, 'day'=>$strippedDay);

    array_push($years, $strippedYear);
    array_push($properDates, $thisDate);
}

我希望最终得到一个多维数组,我可以通过循环获得年/月/日

你们能提供的任何帮助都会很棒。谢谢!

【问题讨论】:

    标签: php wordpress sorting date datetime


    【解决方案1】:

    您可以使用explode。像这样的:

    $dates = ['2019-09-17', '2019-09-16', '2018-08-15', '2017-08-14'];
    
    $result = [];
    
    foreach($dates as $date) {
        $dateParts = explode('-', $date);
        $result[$dateParts[0]][$dateParts[1]][] = $dateParts[2];
    }
    

    会产生

    array(3) {
      [2019]=>
      array(1) {
        ["09"]=>
        array(2) {
          [0]=>
          string(2) "17"
          [1]=>
          string(2) "16"
        }
      }
      [2018]=>
      array(1) {
        ["08"]=>
        array(1) {
          [0]=>
          string(2) "15"
        }
      }
      [2017]=>
      array(1) {
        ["08"]=>
        array(1) {
          [0]=>
          string(2) "14"
        }
      }
    }
    

    如果你想排序,你可以像这样简单地排序:

    foreach($result as &$e){
        ksort($e);
        foreach($e as &$t){
            asort($t);
        }
    }
    
    ksort($result);
    

    ksort(升序)或krsort(降序)将按键排序,sort(升序)或rsort(降序)将按值排序;

    【讨论】:

    • 如果你想对输出进行排序,你应该只在迭代数据之前调用一次sort()。为了唯一性,$result[$dateParts[0]][$dateParts[1]][$dateParts[2]] = $dateParts[2];
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多