我必须从输入表单控件中获取数据范围加上第一个日期的前一天和最后一个日期的后一天,每个控件都具有
dates[]
的名称属性。我试图在迭代 $_POST
值时获取第一个和最后一个日期,如下所示,但最后一次迭代 $_POST['dates]
的最后日期总是丢失。当我注释掉 foreach($dates as $date)
时,我验证了 $dates = explode(',', $dates[$i])
返回了缺失的日期,但无法弄清楚这一行有什么问题。
请帮我找到丢失日期的原因和可能的解决方法。
$ids = $_POST['id'];
$dates = $_POST['dates'];
for($i = 0; $i < count($ids); $i++):
$dates = $_POST['dates'];
$dates = explode(',', $dates[$i]);
$firstDates = array_slice($dates, 0, 1);
$lastDates = array_slice($dates, count($dates) - 1, 1);
foreach($dates as $date):
echo '$dates[$i] are' . $date;
endforeach;
foreach($firstDates as $firstDate):
echo '$firstDate: ' . $firstDate;
endforeach;
foreach($lastDates as $lastDate):
echo '$lastDate is' . $lastDate;
endforeach;
endif;
首先,您的代码有一个错误,即您正在使用 endif closing for 循环。它应该以endfor结束。这是代码的简单版本。试试这个:-
$ids = $_POST['id'];
$dates = $_POST['dates'];
for ($i = 0; $i < count($ids); $i++) :
$dates = explode(',', $dates[$i]);
$firstDates = [];
$lastDates = [];
foreach ($dates as $key => $date) :
if($key == 0) array_push($firstDates,$date);
if($key == count($dates)-1) array_push($lastDates,$date);
echo '$dates[$i] are' . $date;
endforeach;
endfor;