This time to bring you the use of PHP to implement the Turntable lottery algorithm case analysis, the use of PHP to realize the Dial lottery algorithm considerations are what, the following is the actual case, together to see.
Process:
1. Assembling the prize array
2. Calculate probability
3. Return to the winning situation
The code is as follows:
The probability of winning ' V ' can be set in the background, passed to this method, note the integer
function Get_gift () {//Assembled award array//Prize ID, Prize, probability $prize _arr = Array (' 0 ' = = Array (' ID ' =>1, ' prize ' = ' flat Board pc ', ' V ' =>0), ' 1 ' = = Array (' ID ' =>2, ' prize ' = ' digital camera ', ' V ' =>0), ' 2 ' = = Array (' ID ' =>3, ' prize ' = > ' Speaker device ', ' V ' =>0, ' 3 ' = = Array (' ID ' =>4, ' prize ' = ' 4G ', ' V ' =>5), ' 4 ' = = Array (' ID ' =>5, ' p Rize ' = ' 10Q ', ' V ' =>0), ' 5 ' = = Array (' ID ' =>6, ' prize ' + ' void Award ', ' V ' =>5),); foreach ($prize _arr as $key = + $val) {$arr [$val [' id ']] = $val [' V '];//probability array} $rid = $this->get_rand ( $arr); Get the prize ID $res by probability [' yes '] = $prize _arr[$rid -1][' Prize '); Medium Prize unset ($prize _arr[$rid-1]); The prize is excluded from the array and the remaining awards are shuffle ($prize _arr); Scrambled array order for ($i =0; $i <count ($prize _arr); $i + +) {$PR [] = $prize _arr[$i] [' Prize '];//Not in the prize array} $res [' No ' ] = $PR; Var_dump ($res); if ($res [' Yes ']!= ' empty prize ') {$result [' status ']=1; $result [' name ']= $res [' yes ']; }else{$result [' status ']=-1; $result [' msg ']= $res [' yes ']; }//return $result; Var_dump ($result); }//Calculate the probability of winning function Get_rand ($PROARR) {$result = '; The total probability accuracy of the probability array $proSum = Array_sum ($PROARR); Var_dump ($proSum); Probability array loop foreach ($proArr as $key + = $proCur) {$randNum = Mt_rand (1, $proSum);//Return random integer if ($randNum < = $proCur) {$result = $key; Break } else {$proSum-= $proCur; }} unset ($PROARR); return $result; }
:
Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!
Recommended reading:
PHP using file_get_contents to send HTTP request steps in detail
PHP generates two-dimensional code poster case study