Created
January 11, 2016 03:42
-
-
Save lackneets/b5ef4d55b381f0a5a043 to your computer and use it in GitHub Desktop.
公平的資料庫獎項抽獎
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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