【发布时间】:2020-02-04 17:54:49
【问题描述】:
我有一个fiddle,我想在其中计算当月的天数。
我在小提琴中使用的sn-ps代码是:
<?php
$current_month_first_day = new DateTime('first day of this month'); // first day of the current month
$current_month_last_day = date('t'); // last day of the current month
$interval = new DateInterval('P1D');
$period = new DatePeriod($current_month_first_day, $interval, $current_month_last_day - 1);
print_r($period); // Line A
?>
A 行打印:
DatePeriod Object
(
[start] => DateTime Object
(
[date] => 2020-02-01 18:03:30.000268
[timezone_type] => 3
[timezone] => Europe/Amsterdam
)
[current] =>
[end] =>
[interval] => DateInterval Object
(
[y] => 0
[m] => 0
[d] => 1
[h] => 0
[i] => 0
[s] => 0
[f] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] =>
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
[recurrences] => 29
[include_start_date] => 1
)
[recurrences] 在上面的调试中打印29,这意味着当月有 29 天。
php代码:
<!-- YES/NO START -->
<div class="choose-options">
<h4 style="text-align:center;">Yes/No</h4>
<div class="yes-no-option" style="display:inline-grid;">
<?php for ($i=0; $i<=29; $i++ ) { ?> <!-- I have harcoded 29 but it should be coming through php variable --> <!-- Line B -->
<select name="house_sitting_date_yes_no[]" class="house-yes-no" style="height:24px; margin-bottom:20px;">
<option value="nada">Please choose an option</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<?php } ?>
</div>
</div>
<!-- YES/NO END -->
问题陈述:
我想知道我应该在 B 行 的 php 代码 中进行哪些更改,以便它循环 29 次(取决于关于当月的天数。目前,我已经硬编码了 29,但它应该是通过 php 变量来的)。
我想计算天数的原因是我想在 B 行(或 30 次或 31 次) 运行 for 循环 29 次,具体取决于数字的
本月有天数。
【问题讨论】:
-
你知道php已经内置了,对吧?您可以在date function 上使用
t,它也适用于DateTime 对象。 3v4l.org/QT7dK -
您可以只使用
foreach()而不是您从第一个脚本中获得的$period值。 -
<?php for ($i=0; $i<=date('t'); $i++ ) {把剩下的扔掉 -
@RiggsFolly 它有效,谢谢。