3

我需要编写一个 php 脚本,根据用户注册的日期确定用户必须支付的金额。他们注册得越晚,支付的费用就越多,所以这里是脚本的基本代码:

private $date;

function __construct() {
    $this->date = getdate();
}

function get_amount()
{
    $day = $this->date["mday"];
    $month = $this->date["month"];
    $year = $this->date["year"];
    $date = $day.$month.$year;
    switch($date) {
        case "26October2012":
            return "800";
            break;
        case "26Novermber2012":
            return "900";
            break;
    }
}

但显然这个 case 语句不能正常工作。因此,如果用户在 2012 年 10 月 26 日之前注册,那么他们支付 800,如果是在 11 月 26 日之前但在 10 月 26 日之后,那么他们支付 900。那么我该如何编写这个逻辑呢?

4

3 回答 3

4

只需将您的日期转换为 Unix 时间戳,比较它们,让整个事情变得更简单。请参阅strtotime函数。

$compare_date = "2012-10-26";
$todays_date = date("Y-m-d");

$today_ts = strtotime($todays_date);//unix timestamp value for today
$compare_ts = strtotime($compare_date);//unix timestamp value for the compare date

if ($today_ts > $compare_ts) {//condition to check which is greater
   //...
}

strtotime将您的日期时间转换为整数Unix 时间戳。Unix 时间戳定义为自 1970 年 1 月 1 日协调世界时 (UTC) 午夜以来经过的秒数。因此,作为一个整数,它很容易比较,无需字符串操作。

于 2012-10-26T06:06:47.430 回答
0

创建一个包含amount不同日期的数组:

$amountPerDate = array(
    '2012-10-26' => 800,
    '2012-11-26' => 900,
);

循环通过它以获得相应的amount值:

krsort($amountPerDate); // Recursive sort to check greater dates first
$date = strtotime($date);  // Convert '2012-10-23' to its numeric equivalent for the date comprasion
$amount = 0; // Default amount value
foreach ($valuePerData as $date => $amount) {
    if ($date >= strtotime($date)) {
        $amount = $amount;
    }
}
于 2012-10-26T06:19:44.333 回答
0

您不能使用switch语句进行范围比较。

您可以将日期转换为时间戳,然后使用if-else.

于 2012-10-26T06:08:14.063 回答