从数组列表中显示日期

问题描述

我有包含日期​​列表的数组。 我想显示

25 june & 2,9 July 2021

这是我的代码

$dates = array( 
        0 => '2021-06-25',1 => '2021-07-02',2 => '2021-07-09',); 
    
    foreach($dates as $date){
        //$data = DateTime::createFromFormat('F j Y',$date);
        $data = date('j F Y',strtotime($date));
        echo $data . ',';
    }

我尝试创建 Ym-index 但第一个数组丢失了他的月份。

$compare = array();

foreach($dates as $date){
    $data = date('j F',strtotime($date));
    $ym = date('F Y',strtotime($date));
    $date = date('j',strtotime($date));
    //$compare[] = $ym;
    if(!in_array($ym,$compare)){
        
        echo $date . '<br>';
        $compare[] = $ym;
        
    }else{
    
        echo $data . '<br>';
        
    }
    
    
}

输出

25
2
9 July

解决方法

借助按年和月分组的多维辅助数组的解决方案。

输入:

$dates = array( 
        0 => '2021-06-25',1 => '2021-07-02',2 => '2021-07-09',3 => '2020-05-19',);

排序和创建数组:

sort($dates);

$groupes = $helper = [];
foreach($dates as $date){
  list($year,$month,$day) = explode('-',$date);
  $groupes[(int)$year][(int)$month][] = (int)$day;
} 

foreach($groupes as $year => $arr){
  foreach($arr as $month => $dayArr){
    $monthName = date('F',strtotime('2000-'.$month.'-01'));
    $helper[$year][] = implode(',',$dayArr).' '. $monthName;
  }
}

输出:

foreach($helper as $year => $dateStrings){
  echo implode(' & ',$dateStrings).' '.$year."<br>\n";
}

以上数据的输出:

19 May 2020
25 June & 2,9 July 2021
,

第一种方法。它可以改进。它考虑了不同的年份。

$dates = array(
        0 => '2020-06-25',1 => '2021-06-25',2 => '2021-07-02',3 => '2021-07-09'
);

$years = array();

foreach($dates as $date) {
    $day = date('j',strtotime($date));
    $month = date('F',strtotime($date));
    $year = date('Y',strtotime($date));

    if(array_key_exists($year,$years)) {
        if(array_key_exists($month,$years[$year])) {
            $years[$year][$month] .= ',' . $day;
        } else {
            $years[$year][$month] = $day;
        }

    } else {
        $years[$year] = array($month => $day);
    }
}

$showYearSepartor = false;
$showMonthSepartor = false;


foreach($years as $year => $months) {
    if($showYearSepartor) {
        echo ' - ';
    }

    $showYearSepartor = true;

    foreach($months as $month => $day) {
        if($showMonthSepartor) {
            echo ' & ';
        }

        echo $day . ' ' . $month . ' ';

        $showMonthSepartor = true;
    }

    $showMonthSepartor = false;

    echo $year;
}