0

我对 PHP 有点陌生,所以我的脚本编写仍在进行中。我有一个页面,用户注册他们必须付费的研讨会。如果他们在研讨会开始前5天之前注册,他们将获得折扣价,如果他们在研讨会开始前5天注册,他们必须支付全价。我已经编写了一个 PHP 脚本,我认为它会这样做(无论如何都在测试中),但我觉得有更好的编写方法。我只是在寻找任何人的任何建议,如果有的话。非常感谢您的帮助。我的脚本如下。

date_default_timezone_set('MST');
$discount_check  = date("YmdHis", mktime(date("H"), date("i"), date("s"), date("m") , date("d")+5 , date("Y") ));

//Made an array because there are several seminars a year and because I need to make it easy enough for others in my office (who don't know PHP) to add/edit seminar dates
$array = array(
'Utah_seminar' => '20120130153804',
'Seattle_seminar' => '20120723000000',
'Florida_seminar' => '20121005000000'
);

while ($seminar_dates = current($array)) 
{
    if ($discount_check >= $seminar_dates) 
    {
        echo 'discount is not eligible';
        break;
    }
    else
    {
        echo 'discount received';
        break;
    }
next($array);
}

再次,非常感谢任何帮助。即使它发现代码有任何问题。

4

3 回答 3

2
<?
date_default_timezone_set('MST');

$now = new DateTime();

// Made an array because there are several seminars a year and because I need
// to make it easy enough for others in my office (who don't know PHP) to
// add/edit seminar dates
$array = array(
    'Utah_seminar'    => new DateTime('2012-01-30 15:38:04'),
    'Seattle_seminar' => new DateTime('2012-07-23 00:00:00'),
    'Florida_seminar' => new DateTime('2012-10-05 00:00:00')
);

foreach ($array as $seminar => $date) {
    $cutoff = clone $date;
    $cutoff->modify('-5 days');

    if ($now > $cutoff) {
        echo "$seminar - discount is not eligible\n";
    } else {
        echo "$seminar - discount received\n";
    }
}
?>
于 2012-01-26T14:09:12.437 回答
0

因为你正在使用break你的循环只会运行一次。如果我了解您要执行的操作,则应使用:

$eligable = false;
foreach ($array as $seminar_date) {
  if ($discount_check < $seminar_date) {
    $eligable = true;
    break;
  }
}

if ($eligable) {
  echo 'discount received';
} else {
  echo 'discount is not eligible';
}

我将while循环更改foreach为我认为它们更容易理解

于 2012-01-26T14:08:29.783 回答
0

根据您要对数组执行的操作,我建议您进行排序,然后确定第一个适用的索引。

$discount_check = mktime(date());
//Sort array in reverse order
arsort($array);
for($i = 0; $i < count($array);$i++){
    //If array value meets the discount criteria, 
    if($array[$i]  <=   $discount_check - 432000){
    //The index of the first array item to match the discount criteria, since array is sorted all subsquent are applicable
        $split = $i;
        $i = count($i);
    }   
}
于 2012-01-26T14:18:27.817 回答