doulidai6316 2015-08-10 03:30
浏览 27
已采纳

针对DateTime对象的Foreach循环

I'am writing a small program that basically adds a fee to book if it is overdue just like a library.

So my thoughts are for each day that the book is late then there will be a fee added

IE: if the book is overdue for 5 days then the fee would be £10 = £2 a day.

Here is my code so far, not sure if it would be a "foreach" to be honest but i guess so

<?php
class Book
{

public $timeOverdue;

public function isBookOverdue()
{
    $returnedDate = new \DateTime('05/19/2015');
    $dueDate = new DateTime('05/08/2015');

    var_dump('returndDate', $returnedDate);
    var_dump('dueDate', $dueDate);

    if ($returnedDate > $dueDate) {

        echo 'Book is overdue.' . PHP_EOL;
        // $isBookOverdueStatus = true;
        $timeOverdue = date_diff( $returnedDate, $dueDate);
        echo $timeOverdue->format("%m month, %d days (total: %a days)") . PHP_EOL;
        var_dump($timeOverdue);

    } else {
        echo "Book is not overdue" .PHP_EOL. "Book has been returned" . PHP_EOL;
        die();
    }
}
}

$returnOfABook = new Book();
$returnOfABook->isBookOverdue();
$returnOfABook->addOverdueFee();

Then here is kind of what im thinking is possible? more sudo code than anything:

// public function addOverdueFee($timeOverdue)
// {
//   foreach ($timeOverdue as "day" => 1) {
//       // add fee
//   }
// }

and just for reference here is the date object that i want the loop to be running on:

object(DateInterval)#4 (15) {
["y"]=>
int(0)
["m"]=>
int(0)
["d"]=>
int(11)
["h"]=>
int(0)
["i"]=>
int(0)
["s"]=>
int(0)
["weekday"]=>
int(0)
["weekday_behavior"]=>
int(0)
["first_last_day_of"]=>
int(0)
["invert"]=>
int(1)
["days"]=>
int(11)
["special_type"]=>
int(0)
["special_amount"]=>
int(0)
["have_weekday_relative"]=>
int(0)
["have_special_relative"]=>
int(0)
}

So i thinkkkk that it would be something along the lines of this?

foreach($array as $key => $value)
{
  //do stuff
}

Im still learning a lot so any tips, suggestions would be great, Thank you!

展开全部

  • 写回答

1条回答 默认 最新

  • duanfengshang1088 2015-08-10 03:35
    关注

    Just get the number of days the book is overdue and multiply it by 2. You already have everything you need as timeOverdue contains the number of days the book is overdue.

    if ($returnedDate > $dueDate) {
        $timeOverdue = date_diff( $returnedDate, $dueDate);
        $amountToPay = $timeOverdue->days * 2;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部