如何解决从数组列表中显示日期
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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。