我正在撰写客户忠诚度系统。我有一个页面,我输入用户的客户ID和他们花的金额。我想把它写到每花费150美元的地方,他们可以获得20美元的信用额度,但是我遇到了冲击。
假设用户目前的余额为140美元。他们需要再花10美元来获得信贷。但是,如果他们花20美元,他们的余额就会变成160美元而且没有信用额度。
有什么建议吗?
$transac['newBalance'] = $row['balance'] + $transac['amount'];
if ($transac['newBalance']%150 == 0 ) {
// +20 to credit
$transac['newCredit'] = $row['credit'] + 20;
$query = "UPDATE customers SET credit='" . $transac['newCredit'] . "' WHERE userid = '" . $transac['username'] . "'";
if (!mysqli_query($mysqli, $query)) {
die("Query Error (" . $query . "): " . mysqli_error($mysqli));
}
}
答案 0 :(得分:4)
%
在这里是错误的运算符。你想要简单的划分。你可以通过将他们的总支出除以150并逐渐减少来计算出20美元的信用额度。
例如,如果有人花了140美元,140 / 150
向下舍入为0。
如果有人花了310美元,310 / 150
是2.06;四舍五入,你得2,所以他们有2个20美元的学分,或(2 * 20
)40美元。
您可以将PHP的floor
用于向下舍入部分:
$spent = 140.0;
$credits = floor($spent / 150.0) * 20; # 0
$spent = 310.0;
$credits = floor($spent / 150.0) * 20; # 40
答案 1 :(得分:3)
您需要考虑新支出是否使总余额超过150美元的新倍数。
$transac['newBalance'] = $row['balance'] + $transac['amount'];
$oldMultiple = floor($row['balance']/150); //Previous multiple of 150
$newMultiple = floor($transac['newBalance']/150); //Current multiple of 150
$difference=$newMultiple-$oldMultiple; //Are they different?
if ( $difference>0 ) {
// +20 to credit for each multiple of $150 that was passed
$transac['newCredit'] = $row['credit'] + 20 * $difference;
$query = "UPDATE customers SET credit='" . $transac['newCredit'] . "' WHERE userid = '" . $transac['username'] . "'";
if (!mysqli_query($mysqli, $query)) {
die("Query Error (" . $query . "): " . mysqli_error($mysqli));
}
}