以下是一个PHP函数,它可以根据输入的年份和月份输出该月份中星期日的个数:
function countSundays($year, $month) {
$firstDay = date('Y-m-01', strtotime($year . '-' . $month . '-01'));
$lastDay = date('Y-m-t', strtotime($firstDay));
$sundays = 0;
$currentDay = $firstDay;
while ($currentDay <= $lastDay) {
if (date('N', strtotime($currentDay)) == 7) {
$sundays++;
}
$currentDay = date('Y-m-d', strtotime($currentDay . ' +1 day'));
}
return $sundays;
}
// 示例用法
$year = 2022;
$month = 3;
$sundays = countSundays($year, $month);
echo "在" . $year . "年" . $month . "月中,有" . $sundays . "个星期日。";
请注意,此函数假设输入的年份和月份是有效的。如果输入的年份和月份无效,例如月份小于1或大于12,函数可能会产生不正确的结果。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站