將lottery_helper.php
放在你的工程根目錄/application/helpers/git
$this->load->helper('lottery');
//抽獎,返回獎品id $price_id = lottery($arr); echo $price_id;
關於$arr
參數的規範有下面兩種方式:github
$arr = array( array( "id" => 1, "rate" => 0.1, ), array( "id" => 2, "rate" => 0.2345, ), array( "id" => 3, "rate" => 0, ) );
注:算法
(1) id :獎品編號, rate:獎品中獎機率sql
(2) id 從 1 開始遞增數據庫
(3) rate 爲 [0,1]app
$query->result_array()
查詢數據庫後返回的結果$result
$sql = "SELECT `id`,rate FROM `price_table`"; $query = $this->db->query($sql); $result = $query->result_array(); if (is_array($result) && count($result, COUNT_NORMAL) > 0) { return $result; } else { return false; }
以上文方法一:直接傳 array 參數
傳的參數舉例:函數
type | id | rate |
---|---|---|
獎品1 | 1 | 0.1 |
獎品2 | 2 | 0.234 |
獎品3 | 3 | 0 |
未中獎 | 4 | 0.6655 |
type | id | rate |
---|---|---|
獎品3 | 3 | 0 |
獎品1 | 1 | 0.1 |
獎品2 | 2 | 0.234 |
未中獎 | 4 | 0.6655 |
min_rate
= 0.1,並計算每一個獎品的權重值( weight )權重值計算公式:weight = rate / min_ratecodeigniter
type | id | rate | weight |
---|---|---|---|
獎品3 | 3 | 0 | 0 |
獎品1 | 1 | 0.1 | 1 |
獎品2 | 2 | 0.234 | 2.345 |
未中獎 | 4 | 0.6655 | 6.655 |
range_min
, rang_max
],左開右閉落點範圍:this
range_min = 上個獎品的 range_max
range_max = range_min + weight
type | id | rate | weight | range_min | rang_max |
---|---|---|---|---|---|
獎品3 | 3 | 0 | 0 | 0 | 0 |
獎品1 | 1 | 0.1 | 1 | 0 | 1 |
獎品2 | 2 | 0.234 | 2.345 | 1 | 3.345 |
未中獎 | 4 | 0.6655 | 6.655 | 3.345 | 10 |
max_float_length
)type | id | rate | weight | range_min | rang_max |
---|---|---|---|---|---|
獎品2 | 2 | 0.234 | 2.345 | 1 | 3.345 |
未中獎 | 4 | 0.6655 | 6.655 | 3.345 | 10 |
max_float_length = 3.345,即精確位數爲小數點後 3 位
隨機小數範圍 = rand(1 , max(range_max) * pow(10, max_float_length)) / pow(10, max_float_length)
若隨機小數 = 2.175 ,即落在獎品2!