简体   繁体   中英

Foreach two DatePeriod Object

I want to create scheduling for my web. How can I get schedule with 2 days per weeks. Example: show Monday and Friday every week. This is my code:

$day_of_week = "Monday";
$step  = 1;
$unit  = 'W';
$start = new DateTime("");
$end   = clone $start;
$start->modify($day_of_week); // Move to first occurrence
$end->add(new DateInterval('P7W')); // Move to 1 year from start
$interval = new DateInterval("P{$step}{$unit}");
$period   = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
    echo '<tr>';
    echo '<td><a href="lihatAbsen.php?tanggal='.$date->format('d-m-Y').'&id='.$id_kuliah.'">'.$date->format('d M Y').'</td>';
}

$day_of_week2 = "Friday";
$start->modify($day_of_week2); // Move to first occurence
$period2  = new DatePeriod($start, $interval, $end);
foreach ($period2 as $date) {
    echo '<td><a href="lihatAbsen.php?tanggal='.$date->format('d-m-Y').'&id='.$id_kuliah.'">'.$date->format('d M Y').'</td></tr>';
}

Its working but i want to get the $period2 object printed in the same row <tr></tr> with $period object. How to do the right loop? Or how to get 2 days/weeks with input days?

You can manipulate the first date in it's loop and add it to the output text string

$monday=$date->format('d-m-Y');
$friday= date("d-m-Y",strtotime("$monday +4 days"));

Just clone your current $date object and move it to the next Friday.

$day_of_week = "Monday";
$step  = 1;
$unit  = 'W';
$start = new DateTime("");
$end   = clone $start;
$start->modify($day_of_week); 
$end->add(new DateInterval('P7W')); 
$interval = new DateInterval("P{$step}{$unit}");
$period   = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
    echo '<tr>';
    echo '<td><a href="lihatAbsen.php?tanggal='.$date->format('d-m-Y').'&id='.$id_kuliah.'">'.$date->format('d M Y').'</td>';

    $friday = clone $date;
    $friday->modify('next Friday');
    echo '<td><a href="lihatAbsen.php?tanggal='.$friday->format('d-m-Y').'&id='.$id_kuliah.'">'.$friday->format('d M Y').'</td></tr>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM