doulidai6316 2015-08-10 11: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 11: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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!