Функция для вывода календаря на заданный месяц.
function getCalendarForMonth($month, $year)
{
$arMonthDay = array();
$currentDayUnixTime = strtotime(date("{$year}-{$month}-01"));
$currentMonth = date('m', $currentDayUnixTime);
$dayWeekIndex = 1;
$weekIndex = 1;
while($month == $currentMonth) {
$currentDayWeekNumber = date("N", $currentDayUnixTime);
if($currentDayWeekNumber == $dayWeekIndex) {
$arMonthDay[$weekIndex][$dayWeekIndex] = date('d', $currentDayUnixTime);
$currentDayUnixTime = strtotime("+1 day", $currentDayUnixTime);
$currentMonth = date('m', $currentDayUnixTime);
}
else {
$arMonthDay[$weekIndex][$dayWeekIndex] = "";
}
if($dayWeekIndex == 7) {
$weekIndex++;
$dayWeekIndex = 1;
}
else {
$dayWeekIndex++;
}
}
if(!empty($arMonthDay[$weekIndex])) {
$arMonthDay[$weekIndex] = array_pad($arMonthDay[$weekIndex], 7, "");
}
return $arMonthDay;
}
Пример
Теперь используя эту функцию можно вывести календарь, например на ноябрь 2017 года
<?php $arMonthDay = getCalendarForMonth(11, 2017); ?>
<table class="table">
<thead>
<th>Пн</th>
<th>Вт</th>
<th>Ср</th>
<th>Чт</th>
<th>Пт</th>
<th>Сб</th>
<th>Вс</th>
</thead>
<tbody>
<?php foreach($arMonthDay as $arWeek) { ?>
<tr>
<?php foreach($arWeek as $day) { ?>
<td><?php echo $day;?></td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
В результате получится примерно следующая таблица:
Пн | Вт | Ср | Чт | Пт | Сб | Вс |
---|---|---|---|---|---|---|
01 | 02 | 03 | 04 | 05 | ||
06 | 07 | 08 | 09 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Доработки
В зависимости от задачи функцию можно доработать, например добавить отметку о том что день является текущим (сегодняшним).
function getCalendarForMonth($month, $year)
{
$arMonthDay = array();
$currentDayUnixTime = strtotime(date("{$year}-{$month}-01"));
$currentMonth = date('m', $currentDayUnixTime);
$dayWeekIndex = 1;
$weekIndex = 1;
while($month == $currentMonth) {
$currentDayWeekNumber = date("N", $currentDayUnixTime);
if($currentDayWeekNumber == $dayWeekIndex) {
$arMonthDay[$weekIndex][$dayWeekIndex] = array(
"day" => date('d', $currentDayUnixTime),
"today" => (date("Y-m-d") == date("Y-m-d", $currentDayUnixTime))
);
$currentDayUnixTime = strtotime("+1 day", $currentDayUnixTime);
$currentMonth = date('m', $currentDayUnixTime);
}
else {
$arMonthDay[$weekIndex][$dayWeekIndex] = array(
"day" => "",
"today" => false
);
}
if($dayWeekIndex == 7) {
$weekIndex++;
$dayWeekIndex = 1;
}
else {
$dayWeekIndex++;
}
}
if(!empty($arMonthDay[$weekIndex])) {
$arMonthDay[$weekIndex] = array_pad($arMonthDay[$weekIndex], 7, array(
"day" => "",
"today" => false
));
}
return $arMonthDay;
}