【发布时间】:2011-11-01 23:20:03
【问题描述】:
我正在我的网站上运行订阅。 我有 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 .97
【问题讨论】:
-
他从什么变成什么?例如,我订阅了 12 个月,我订阅了第 2 个月,现在我将订阅更改为 3 个月,您将所有这些值存储在哪里?
-
这只是有关此功能用途的一些概述。如果您全年(12 个月)支付 25.99,并在 7 个月后进行纾困或升级,则视为您拥有 6 个月 + 1 个月。并从您已经支付的先前 25.99 中获得退款。在这里你可以看到它是:refund=25.99-(15.99+3.99)=6.01 如果你把这个函数运行起来,10次后你可以看到输出是错误的。比如“10 个月的 OPT 值=M.97”,其中 M.97 很奇怪。我正在试图找出是什么原因造成的。
-
我没有测试代码,因为我目前没有PHP服务器,如果还有问题,请告诉我。
-
是的。仍然发生......这一定是内存泄漏