为什么不能在php中获得周末的价值

时间:2017-09-06 05:19:14

标签: php

我不知道这段代码的错误是什么,因为突然不准确显示给用户的价值如下:
enter image description here

  $holidays = array();
        $query_holiday = "SELECT * FROM holiday_tbl";
         $result = mysqli_query($dbcon, $query_holiday);
         while($row_holiday = mysqli_fetch_assoc($result))
  {
     array_push($row_holiday, $holidays);
  }


if(strtotime(date("Y-m-d")) > strtotime($row['due_date']))
{

$currentDate = date("Y-m-d");
$days = (strtotime($currentDate) - strtotime($row['due_date'])) / 86400;
$daysTemp = $days;
for($i=1;$i<$days;$i++)
{
    $currentDay = date("D", strtotime("+ ".$i." days"));
    $date_loop =  date("Y-m-d", strtotime("+ ".$i." days"));
    if($currentDay == "Sun" || $currentDay == "Sat")
    {
        $daysTemp--;
    }
    else if(in_array($date_loop, $holidays))
    {
       $daysTemp--;
     }
}
echo $daysTemp;
}

1 个答案:

答案 0 :(得分:1)

目前的实施相当复杂。在这些情况下,我发现重新开始并尝试尽可能简化逻辑总是更好。以下是我对你的问题的看法:

function calculate_days_late($due_date = '', $holidays = array(), $current_date = 'today') {
    $days_late = 0;

    // Get the timestamps for due date and current date
    $current_date_ts = strtotime($current_date);
    $due_date_ts = strtotime($due_date);

    // If current date is not after due date then not late
    if ($current_date_ts <= $due_date_ts) {
        return $days_late;
    }

    $loop_date_ts = $current_date_ts;
    while ($loop_date_ts > $due_date_ts) {

        // If the looping date is not a weekend or holiday then count it
        if ( ! in_array(date('D', $loop_date_ts), array('Sat','Sun'))
            && ! in_array(date('Y-m-d', $loop_date_ts), $holidays)) {
            $days_late++;
        }

        $loop_date_ts = strtotime('-1 day', $loop_date_ts);
    }

    return $days_late;
}

// Test
echo '2017-09-05 = ' . calculate_days_late('2017-09-05', array(), '2017-09-05') . "\n";
echo '2017-09-06 = ' . calculate_days_late('2017-09-05', array(), '2017-09-06') . "\n";
echo '2017-09-07 = ' . calculate_days_late('2017-09-05', array(), '2017-09-07') . "\n";
echo '2017-09-08 = ' . calculate_days_late('2017-09-05', array(), '2017-09-08') . "\n";
echo '2017-09-09 = ' . calculate_days_late('2017-09-05', array(), '2017-09-09') . "\n";
echo '2017-09-10 = ' . calculate_days_late('2017-09-05', array(), '2017-09-10') . "\n";
echo '2017-09-11 = ' . calculate_days_late('2017-09-05', array(), '2017-09-11') . "\n";
echo '2017-09-12 = ' . calculate_days_late('2017-09-05', array(), '2017-09-12') . "\n";
echo '2017-09-13 = ' . calculate_days_late('2017-09-05', array(), '2017-09-13') . "\n";

工作示例:https://eval.in/856018