我试图比较我从用户那里获得的数字和存储在数据库中的数字。
基本上,我正在做一个奖励系统,其中达到一定数量积分的用户将获得徽章。现在,我正在做的是,代码将计算用户拥有的点并将其发送到具有if else的函数,以比较每个徽章的点数和值。我现在要做的是,通过将每个徽章的值放在数据库中使其更简单,以便下次我可以更新数据库而不更新代码。以下是我现在正在做的事情。
//check total points that the user has
public function totalPointsValue($userId) {
$value = Yii::app()->db->createCommand()
->select('sum(totalPoints) as pointsSum')
->from('fndn_UserTotal')
->where('userId =:id', array(':id'=>$userId))
->queryRow();
$totalPoints = $value['pointsSum'];
return $totalPoints;
}
//checks whether the user points is enough for a badge
public function checkEligable($userId){
$points = $this->totalPointsValue($userId);
//is not eligable for a badge
if ($points <100){
error_log(" $userId has less than 100 points. Number of points is $points ");
}
//eligable for the over 100 points badge
elseif ($points > 100 && $points <1000){
error_log(" $userId is eligable for over-100 badge. Number of points is $points ");
}
//eligable for the over 1000 points badge
elseif ($points > 1000 && $points <2000){
error_log(" $userId is eligable for over-1000 badge. Number of points is $points ");
}
//eligable for the over 2000 points badge
else {
error_log(" $userId is eligable for over-2000 badge. Number of points is $points ");
}
error_log(print_r($points, true), 3, 'debug.log');
}
我想这样做,以便代码检查数据库中的值并将其与$ points进行比较。下面是我的徽章db。
==============
id badgeName requiredPoints
1 over100 100
2 over500 500
3 over1000 1000
4 over2000 2000
所以,假设用户有600分,它将检查用户有权获得哪个徽章。如果$ points&gt; requirePoints,它将授予用户徽章。
答案 0 :(得分:0)
让我们说你有桌子和桌子型号名称Badge。
编辑: 如果您只想要最接近用户获得的徽章等级
function getBadgesOfUser($points){
$achive_badges = "";
$badges = CHtml::listData(Badge::model()->findAll(array(
'order'=>'requiredPoints', // ASC
'condition'=>'requiredPoints>=:rqp',
'params'=>array('rqp'=>$points))), 'badgeName', 'requiredPoints');
if(count($badges)>0){
//php 5.4
$achive_badges = array_keys($badges)[0]; // I don't use array_shift in this line because it would cause the warning raising in some cases.
//following for PHP 5.3
$temp = array_keys($badges); $achive_badges = $temp[0];
}
return $achive_badges;
}
我使用比较运算符对查询进行排序,这意味着requirePoints
列的数据类型必须是数字(int,decimal等)