用PHP函数知识来实现年历的制作
时间: 2024-05-05 11:15:55 浏览: 56
以下是一个简单的PHP函数来制作年历:
```php
function createCalendar($year) {
// 设置每个月的天数
$daysInMonth = array(31, 28 + isLeapYear($year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
// 设置月份和星期几的名称
$months = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$daysOfWeek = array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
// 用表格形式输出日历
echo "<table>";
// 输出年份
echo "<tr><th colspan='7'>$year</th></tr>";
// 循环输出每个月的日历
for ($month = 0; $month < 12; $month++) {
// 输出月份名称
echo "<tr><th colspan='7'>$months[$month]</th></tr>";
// 输出星期几的名称
echo "<tr>";
foreach ($daysOfWeek as $day) {
echo "<td>$day</td>";
}
echo "</tr>";
// 输出日期
$date = mktime(0, 0, 0, $month + 1, 1, $year);
$dayOfWeek = date("w", $date);
$numDays = $daysInMonth[$month];
$dayCount = 1;
echo "<tr>";
for ($i = 0; $i < $dayOfWeek; $i++) {
echo "<td></td>";
}
while ($dayCount <= $numDays) {
if ($dayOfWeek == 7) {
echo "</tr><tr>";
$dayOfWeek = 0;
}
echo "<td>$dayCount</td>";
$dayCount++;
$dayOfWeek++;
}
while ($dayOfWeek != 7) {
echo "<td></td>";
$dayOfWeek++;
}
echo "</tr>";
}
echo "</table>";
}
// 判断是否是闰年
function isLeapYear($year) {
return ($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0;
}
// 调用函数
createCalendar(2022);
```
这个函数会创建一个包含指定年份所有月份的日历表格。它使用了date()函数来获取每个月份的第一天是星期几,然后使用循环和条件语句来输出日期。
阅读全文