以年月php日期为单位分组日期


Group date in month and year php date

我有值

2016年5月5日,2016年5月19日,2016年5月26日,2016年6月2日,2016年6月16日,2016年6月23日,2016年7月7日,2016年7月14日

我如何用PHP将其显示为:

2016年5月5日,19日,26日
2016年6月2日、16日、23日
07,14七月2016

假设数组是有序的,那么类似于这段代码的东西应该可以工作:

<?php
$str = '05 May 2016, 19 May 2016, 26 May 2016, 02 June 2016, 16 June 2016, 23 June 2016, 07 July 2016, 14 July 2016';
$arr = explode(',',$str); //
$results = array();
$currResStr = '';
$lastMonth = '';
$lastYear = '';
$appendMonth = false;
$elCount = count($arr);
for ($i=0; $i < $elCount; $i++) {
    preg_match("/([0-9]{2})'s([a-zA-z]+)'s([0-9]*)/", $arr[$i], $match);
    if($i+1 < $elCount){
        preg_match("/([0-9]{2})'s([a-zA-z]+)'s([0-9]*)/", $arr[$i+1], $match2);
        if($match[2] !== $match2[2]){
            $appendMonth = true;
        }else{
            $appendMonth = false;
        }
        if($appendMonth || $i+1 >= count($arr)){
            $currResStr .= $match[1].' '.$match[2].' '.$match[3];
            array_push($results,$currResStr);
            $currResStr = '';
        }else{
            $currResStr .= $match[1].',';
        }
    }else{
        $currResStr .= $match[1].' '.$match[2].' '.$match[3];
        array_push($results,$currResStr);
    }
}
var_dump($results);
?>

打印输出:

array(3) { [0]=> string(17) "05,19,26 May 2016" [1]=> string(18) "02,16,23 June 2016" [2]=> string(15) "07,14 July 2016" }

这是我的三个步骤:

  1. 逗号分隔
  2. 循环以分配用于对日期进行分组的临时键
  3. 循环以显示值

代码:

$string='05 May 2016, 19 May 2016, 26 May 2016, 02 June 2016, 16 June 2016, 23 June 2016, 07 July 2016, 14 July 2016';
foreach(explode(', ',$string) as $date){
    $groups[substr($date,3)][]=substr($date,0,2);
}
foreach($groups as $monthyear=>$days){
    echo implode(',',$days)," $monthyear<br>";
}

输出:

05,19,26 May 2016
02,16,23 June 2016
07,14 July 2016

对于相同的结果,你可以在第一个循环中使用第二个爆炸,如下所示:

foreach(explode(', ',$string) as $date){
    $parts=explode(' ',$date,2);
    $groups[$parts[1]][]=$parts[0];
}
foreach($groups as $monthyear=>$days){
    echo implode(',',$days)," $monthyear<br>";
}