Php random lottery
Obtain the random lottery result based on the set probability.
$ Award) {self ::$ proSum + = $ award [self ::$ proField];} if (empty (self ::$ proSum) {return self :: $ checkAward = false;} return self: $ checkAward = true;} protected static function successRoll ($ rollKey) {return array ('code' => self: SUCCESS_CODE, 'roll _ key' => $ rollKey, 'MSG '=> 'roll success');} protected static function failRoll ($ msg = 'roll fail ') {return array ('code' => self: FAIL_CODE, 'MSG '=> $ Msg) ;}// lottery public static function roll () {if (false = self ::$ checkAward) {return self :: failRoll ('Awards data is not the right format! ') ;}$ Result = mt_rand (0, self: $ proSum); $ proValue = 0; foreach (self ::$ awardsArr as $ _ key => $ value) {$ proValue + = $ value [self: $ proField]; if ($ result <= $ proValue) {return self: successRoll ($ _ key );}} return self: failRoll ('wrong ');} // change the probability field name public static function setProField ($ field = null) {if (! Empty ($ field) {self ::$ proField = $ field ;}// set the public static function setAwards ($ awards) {self ::$ awardsArr = $ awards; self: checkAwards ();}}
Forexample
$ Awards = array ('0' => array ('pro' => 15, 'info' => 'likelihood of 15% '), '1' => array ('pro' => 25, 'info' => '25% likelihood '), '2' => array ('pro' => 40, 'info' => '1970 probability '), '3' => array ('pro' => 20, 'info' => '1970 probability '),); lottery_tool: setProField ('pro'); lottery_tool: setAwards ($ awards); $ result = array (); for ($ I = 10000; $ I --;) {$ result [] = lottery_tool: roll ();} foreach ($ result as $ key => $ value) {$ awards [$ value ['roll _ key'] ['num'] ++;} echo''; Var_dump ($ awards); // result: array 0 => array 'pro' => int 15 'info' => string '15% likelihood' (length = 15) 'num' => int 1596 1 => array 'pro' => int 25 'info' => string 'likelihood of 25% '(length = 15) 'num' => int 2484 2 => array 'pro' => int 40 'info' => string 'likelihood of 40% '(length = 15) 'num' => int 3939 3 => array 'pro' => int 20 'info' => string 'likelihood of 20% '(length = 15) 'num' => int 1981