问题
Trying to make a for loop that has the HHMM outputted in a data-time HTML field.
I currently have:
for ($i = 1; $i <= 20; ++$i) {
echo '<div class="mb-timer-hour"><div class="mb-timer-half" data-time="0830"></div></div>';
}
Except this outputs data-time="0830" every time.
I then tried $h = 30; $h + 30 but this then goes: 0800, 0830, 0860, 0890, ...
Is it possible to loop 0800, 0830, 0900, 0930, ...?
The start time and end times are user variables which is why I haven't hard coded an array.
The output I was hoping for was:
<div class="mb-timer-hour"><div class="mb-timer-half" data-time="0830"></div></div>
<div class="mb-timer-hour"><div class="mb-timer-half" data-time="0930"></div></div>
<div class="mb-timer-hour"><div class="mb-timer-half" data-time="1030"></div></div>
...
<div class="mb-timer-hour"><div class="mb-timer-half" data-time="1730"></div></div>
回答1:
You can use DateTime objects and always add 30 minutes (or 60 minutes) until the end time is reached. The format method is used in the loop to output the times.
$start = '0830';
$end = '1230';
$date_end = date_create($end);
for($date = date_create($start);$date <= $date_end; $date->modify('+30 Minutes')){
echo '<div class="mb-timer-hour"><div class="mb-timer-half" data-time="'.$date->format('Hi').'"></div></div>';
}
The HTML output in a loop is not nice. I took it from the question. If the test runs in the browser, the page source text must be viewed for the result.
回答2:
The way I ended up solving this was with the following code:
$mb_timer_start = strtotime( 'today 0800' );
$mb_timer_end = strtotime( 'today 1800' );
<div class="mbcontainer mb-timer">
<div class="mb-timer-container">
<!-- this is related to: https://stackoverflow.com/a/59637684/1086990 -->
<div class="mb-marker"></div>
<?php
// loop through start H until end H
for( $i = date('H', $mb_timer_start); $i < date('H', $mb_timer_end); ++$i ) {
echo '<div class="mb-timer-hour" style="width:calc(100% / ' . $mb_timer_diff . ');" data-time="' . str_pad($i, 2, '0', STR_PAD_LEFT) . '00">';
echo '<div class="mb-timer-half" data-time="' . str_pad($i, 2, '0', STR_PAD_LEFT) . '30"></div>';
echo '</div>';
}
?>
</div>
</div>
This code changed with the addition of the hour data-time too but the looping was still the question.
来源:https://stackoverflow.com/questions/59610890/how-would-you-loop-every-30-minutes