Skip to content

Instantly share code, notes, and snippets.

@lackneets
Created January 11, 2016 03:42
Show Gist options
  • Save lackneets/b5ef4d55b381f0a5a043 to your computer and use it in GitHub Desktop.
Save lackneets/b5ef4d55b381f0a5a043 to your computer and use it in GitHub Desktop.
公平的資料庫獎項抽獎
<?php
/*
0 4 4 4 7 10000 15300 17200
| 金槌 | 手機 | 吹風機 | Coach 隨手包 | ... | ... | 環保筷 | 商品抵用券 |
↑ ( 隨機數字 12345 )
*/
class GiftShuffler {
private $randsamples = array();
private $samplestotal = 0;
function __construct($db){
$rows=$db->rows("select * from gifttable");
foreach($rows as $gift){
array_push($this->randsamples, array(
'id' => $gift['id'],
'name' => $gift['name'],
// 建立獎項分配數線
'rangeFrom' => $this->samplestotal,
'rangeTo' => $this->samplestotal + $gift['total'] - $gift['hasget'], // 可中獎長度必須扣掉已送出的數量
'dailyTotal' => $gift['dailyget'],
'dailySent' => ($gift['pagedate'] == date('Y-m-d')) ? $gift['hasdailyget'] : 0, //如果 pagedate 是今天,表示 hasdailyget 代表今天所送出
'lastSent' =>$gift['pagedate'],
'total' => $gift['total'],
'totalSent' => $gift['hasget']
));
// 紀錄數線終點
$this->samplestotal += ($gift['total'] - $gift['hasget']);
}
}
public function sample(){
$get = mt_rand(0, $this->samplestotal-1);
foreach ($this->randsamples as $gift) {
//如果隨機數字在獎項的區段,那就是這個獎項了
if($get >= $gift['rangeFrom'] and $get < $gift['rangeTo']){
if($gift['dailySent'] >= $gift['dailyTotal']){
return false; // 本日獎項已配送完
}
return $gift;
}
}
return false;
}
}
$shuffler = new GiftShuffler($db);
$gift = $shuffler->sample();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment