我是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);
}
再一次,非常感谢任何帮助。即使它发现代码有任何问题。
答案 0 :(得分: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";
}
}
?>
答案 1 :(得分: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
因为我认为它们更容易理解
答案 2 :(得分: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);
}
}