我想在foreach循环中显示两个日期之间的日期。 假设日期从2014年5月1日开始到2014年5月3日结束。我想要显示如下
//单独使用for循环,这将显示我想要的内容
for($i=$dateFrom;$i<=$dateTo;$i++) {
echo $i."<br>";
}
May 1,2014
May 2, 2014
May 3, 2014
但是当使用foreach循环显示它是模板
时,此代码返回May 3,2014
May 3, 2014
May 3, 2014
这是我在action.php中的代码
$dateTo = $r->getParameter("date_to", date('Y-m-d'));
$dateFrom = $r->getParameter("date_from", date('Y-m-d', strtotime('7 days ago', strtotime($dateTo))));
$this->data=array();
foreach($this->deposits as $d) {
$obj = new stdClass();
$obj->created_by = $d->created_by;
$obj->date_created = $d->date_created;
for($i =$dateFrom;$i <= $dateTo;$i++) {
$date=$i;//I think the problem is here.I am not sure how to make this work
}
$obj->amount = $d->amount;
$obj->dateCovered = $date;
$this->data[] = $obj;
}
的template.php
<?php foreach ($data as $i => $d): ?>
<tr class="<?php echo ($i%2==0)?'even':'odd' ?>">
<td><?php echo $d->id ?></td>
<td>
<?php echo $d->dateCovered ?>//this will display the last date only
</td>
<td>
<?php $amountTotal += $d->amount ?>
PHP <?php echo number_format($d->amount, 2) ?>
</td>
<td><?php echo $d->created_by ?></td>
<td><?php echo date("F d, Y",strtotime($d->date_created)) ?></td>
</tr>
<?php endforeach ?>
我的问题是它没有显示两个日期之间的所有日期。相反它只会显示两个日期之间的最后日期。这段代码出了什么问题?
答案 0 :(得分:1)
你可以这样做
$date_from = strtotime("1 May 2015");
$date_to = strtotime("15 May 2015");
$oneDay = 60*60*24;
for($i=$date_from; $i<=$date_to; $i=$i+$oneDay)
{
echo date("F j, Y", $i) . "<br>";
}
现在你可以试试这个..
$dateTo = $r->getParameter("date_to", date('Y-m-d'));
$dateFrom = $r->getParameter("date_from", date('Y-m-d', strtotime('7 days ago', strtotime($dateTo))));
$oneDay = 60*60*24;
$date_time = strtotime($dateFrom);
$this->data=array();
foreach($this->deposits as $d) {
$obj = new stdClass();
$obj->created_by = $d->created_by;
$obj->date_created = $d->date_created;
$date= date("F j, Y", $date_time);
$date_time += $oneDay;
$obj->amount = $d->amount;
$obj->dateCovered = $date;
$this->data[] = $obj;
}
答案 1 :(得分:0)
<?php
$date_from = strtotime("10 September 2000");
$date_to = strtotime("15 September 2000");
$day_passed = ($date_to - $date_from); //seconds
$day_passed = ($day_passed/86400); //days
$counter = 1;
$day_to_display = $date_from;
while($counter < $day_passed){
$day_to_display += 86400;
echo date("F j, Y \n", $day_to_display);
$counter++;
}
?>