我正在我的网站上运行订阅。 我有1,3,6和12个月的订阅,我希望用户能够随时更改订阅。 但是,我需要计算用户在短期内报名时需要支付的金额,而不是相对便宜,较长的金额。
我创建了这个函数optimized_subscription_total($active_sub_time,$arr_sub_values)
,以便它准确地返回这笔钱。
<?php
function optimized_subscription_total($active_sub_time,$arr_sub_values)
{
// This function takes a row from the DB where prices for each period of time usage is listed. there are prices for 1 month, 3 months,6 and 12 months.
// when the user has subscribed for 12 months, and the user asks for a refund, after they used 9 months and 6 days for example, the system treats the refund as if they subscribed for (in months) COST_6 + COST_3 + (COST_1/30)*6
// the result of the function is then subtracted from the amount they actually paid and is considered the refund.
// $arr_sub_values is the associative row from the DB, containing the prices
// $active_sub_time is measured in months and is a double
$result=0;
while(($active_sub_time-12)>=0)
{
$active_sub_time-=12;
$result+=($arr_subscription_values['COST_12']);
}
while(($active_sub_time-6)>=0)
{
$active_sub_time-=6;
$result+=($arr_subscription_values['COST_6']);
}
while(($active_sub_time-3)>=0)
{
$active_sub_time-=3;
$result+=($arr_subscription_values['COST_3']);
}
while(($active_sub_time-1)>=0)
{
$active_sub_time-=1;
$result+=($arr_subscription_values['COST_1']);
}
if($active_sub_time>0)
$result+=($active_sub_time)*($arr_subscription_values['COST_1']);
return $result;
}
$datetime1 = date_create('2009-12-11');
$datetime2 = date_create('2010-11-09');
$interval = date_diff($datetime1, $datetime2);
$num_of_months = ($interval->format('%y'))*12+($interval->format('%m'))+($interval->format('%a'))/30;
echo "<br />";
$v = array('COST_1'=>'3.99','COST_3'=>'9.99','COST_6'=>'15.99','COST_12'=>'25.99');
echo "OPT value for $num_of_months months=" . optimized_subscription_total($num_of_months, $v);
?>
奇怪的是,在刷新此代码后,我只会在7到10次后出现错误。 所以我得到了:
OPT value for 10 months=M.97
因此在这里。我想我需要一个浮点数,不是吗?
我期待功能的结果应该是“10个月的OPT值= 29.97”,因为它应该花费COST_6 + COST_3 + COST_1 ......但是我得到了奇怪的M.97,有时像POKHHHG这样的东西0.97
答案 0 :(得分:0)
我会将逻辑更改为以下内容并查看是否仍然生成错误。我认为这是一个更清晰,更容易调试。虽然只是用不同的方式解释,但它与你的相同。
while($active_sub_time>=12)
{
$active_sub_time-=12;
$result+=($arr_subscription_values['COST_12']);
}
while($active_sub_time>=6)
{
$active_sub_time-=6;
$result+=($arr_subscription_values['COST_6']);
}
while($active_sub_time>=3)
{
$active_sub_time-=3;
$result+=($arr_subscription_values['COST_3']);
}
while($active_sub_time>=1)
{
$active_sub_time-=1;
$result+=($arr_subscription_values['COST_1']);
}
我还要做的是在函数顶部添加debug cod。
echo "<br>$active_sub_time" // debug code include at the top
如果有任何垃圾被发送到函数本身,这将给你一个想法。
如果上述方法无法解决问题,我还会在所有块中添加此测试功能。
if (!is_numeric($result))
{
echo"<br> Bug occurred";break; // print other values if necessary
}