如果在一个循环中产生如何跳过的日期?

问题描述 投票:-2回答:1

这段代码的含义: 它根据所前($date)抓住了一天的日期。它总是向上计数一个星期。例如。如果您的开始日期($date)是07.04.2019它会产生$final_amount倍的日期。

所以,如果日期的开始是07.04.2019$final_amount是:5它会输出:

07.04.2019` (handled in separate code, as the first day is excluded in code!)
14.04.2019
21.04.2019
28.04.2019
05.04.2019

我的代码的问题: 我需要跳过,如果它落入放假日期。因此,如果如21.04.2019是一个节日,它应该被忽略,一个星期后,一个新的日期代替。它应该始终有量$final_amount即使一个或多个日期铺设在度假。我不知道这到底是怎么来完成,因为我是比较新的PHP。

setlocale(LC_TIME, "de_DE"); //only necessary if the locale isn't already set
$date = new DateTime(helper('com://site/ohanah.date.format', array(
   'date' => $event->start,
   'format' => 'Y-m-d H:i',
   'timezone' => 'UTC'
)));

$date_scn = new DateTime(helper('com://site/ohanah.date.format', array(
   'date' => $event->end,
   'format' => 'H:i',
   'timezone' => 'UTC'
)));

$cnt = 2; // start the termin to count at two as the first one is already defined above
$raw_ticket_type = $event->ticket_types->name;
$filter_numbers = array_filter(preg_split('/\D/', $raw_ticket_type));
$filtered_numbers = reset($filter_numbers);
$first_occurence = substr($filtered_numbers[0], 0, 1);
$final_amount = $first_occurence - 1; // subtract 1 from $first_occurence as it is always one more

for ($i = 0; $i < $final_amount; $i++)
{ // loop
    $date-- > add(new DateInterval('P1W')); //add one week
    $formatted_time = utf8_encode(strftime("%A, %d. %B %Y, %H:%M", $date->getTimestamp()));
    $formatted_time_scnpart = utf8_encode(strftime("%H:%M", $date_scn->getTimestamp()));

    // This is the modal

    echo '<div class="termin-layout"><span class="termin-number-text">' . $cnt++ . '. ' . 'Termin' . '</span>
<span class="termin-date">' . $formatted_time . ' - ' . $formatted_time_scnpart . '</span></div>';
}

echo '</div></div></div>';
php date datetime
1个回答
1
投票

您可以使用while循环,而不是for循环。然后,如果条件满足,你可以跳过增加计数器。

$i = 0;
while ($i < $final_amount) {
    $date-- > add(new DateInterval('P1W'));
    if (is_holiday($date)) {
        continue;
    }
    $i++;
    $formatted_time = utf8_encode(strftime("%A, %d. %B %Y, %H:%M", $date->getTimestamp()));
    $formatted_time_scnpart = utf8_encode(strftime("%H:%M", $date_scn->getTimestamp()));

    // This is the modal

    echo '<div class="termin-layout"><span class="termin-number-text">' . $cnt++ . '. ' . 'Termin' . '</span>
<span class="termin-date">' . $formatted_time . ' - ' . $formatted_time_scnpart . '</span></div>';
}
© www.soinside.com 2019 - 2024. All rights reserved.