[英]How to assign and retrieve values in array with if condition in php
我需要在 if 條件下為年份分配工作日,例如如果年份是 1995 則 240 個工作日,如果年份是 1996 242 個工作日。等等.. 而不是給每年的 if 條件,是否可以存儲值以數組形式與 if 條件? 嘗試的是
if ( $_GET['year_attend'] == 1995) { $work_days = '140';}
if ( $_GET['year_attend'] == 1996) { $work_days = '142';}
這完全取決於您如何定義休息日。
如果您假設一周有兩個休息日(例如周六和周日)並且您想計算除休息日之外的所有工作日數,那么 -
function isLeapYear($year) {
return ($year % 4 == 0) && ($year % 100 !== 0 || $year % 400 === 0);
}
function getWorkingDays($year) {
$totalDays = isLeapYear($year) ? 366 : 365;
$firstDay = (new DateTime("01-01-$year"));
$offDays = ['Saturday', 'Sunday'];
$leaves = 0;
$interval = new DateInterval('P1D');
for ($day = 1; $day <= $totalDays; $day++) {
// Check if the day is a off-day or not. If off-day then increment the leave count.
if (in_array($firstDay->format('l'), $offDays)) {
$leaves++;
}
// Shift the day to the next date by adding one day interval.
$firstDay->add($interval);
}
// Calculate the total working days by subtracting the leaves from the total days.
$totalWorkDays = $totalDays - $leaves;
return $totalWorkDays;
}
$data = [];
for ($i = 1994; $i <= 2020; $i++) {
$data[$i] = getWorkingDays($i);
}
var_dump($data);
如果您有其他off-days
列表,則在循環內檢查該日期是否包含在休息日列表中。 如果包括在內,則增加休假計數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.