每月循环一系列日期和组

时间:2017-04-04 20:18:17

标签: php arrays loops date

使用PHP,我希望能够遍历一系列日期并显示按月分组的日期。

最终结果如下:

March 24th, 31st
April 7th, 14th, 21st, 28th

ETC

这是阵列。

Array ( [0] => 2017-03-24 [1] => 2017-03-31 [2] => 2017-04-07 [3] => 2017-04-14 [4] => 2017-04-21 [5] => 2017-04-28 [6] => 2017-05-05 [7] => 2017-05-12 [8] => 2017-05-19 [9] => 2017-05-26 [10] => 2017-06-02 [11] => 2017-06-09 [12] => 2017-06-16 [13] => 2017-06-23 [14] => 2017-06-30 [15] => 2017-07-07 [16] => 2017-07-14 [17] => 2017-07-21 [18] => 2017-07-28 [19] => 2017-08-04 [20] => 2017-08-11 [21] => 2017-08-18 [22] => 2017-08-25 [23] => 2017-09-01 [24] => 2017-09-08 [25] => 2017-09-15 [26] => 2017-09-22 [27] => 2017-09-29 [28] => 2017-10-06 [29] => 2017-10-13 [30] => 2017-10-20 [31] => 2017-10-27 )

2 个答案:

答案 0 :(得分:2)

$dates = array('2017-03-24', '2017-03-24', '2017-04-07', '2017-04-14', '2017-04-21', '2017-04-28');
$months = array();
foreach ($dates as $date_str) {
  $timestamp = strtotime($date_str);
  $month = date('F', $timestamp);
  $date = date('jS', $timestamp);

  if (empty($months[$month])) {
      $months[$month] = array();
  }

  $months[$month][] = $date;
}

foreach ($months as $month => $dates) {
  echo $month . " " . implode(", ", $dates) . "<br />";
}

答案 1 :(得分:0)

与已接受的答案相同的概念,但有DateTime个函数和$months = array_reduce($dates, function($months, $date) { $date = new DateTime($date); $months[$date->format('F')][] = $date->format('jS'); return $months; }); 个对象。

按月分组数组:

array_walk($months, function($days, $month) {
    echo "$month ". implode(', ', $days) . '<br>';
});

输出每个月的日期:

(