Php provides a lottery function example to customize the number and probability of winning items.
This example describes how to use php to customize the number and probability of winning items. We will share this with you for your reference. The details are as follows:
<? Php/** one lucky draw class, accurate to one in ten * three steps: 1. accept an array of winning probability values; 2. accept a lucky draw. 3. return the winning level */class Lottery {/** array of winning probability, and automatically judge the number of awards * array. The key value is 100, and the probability of not winning is automatically calculated, if the initial value is more than 100, an error is thrown */protected $ _ rate = array ();/** sets the winning probability. * @ param Array indicates the winning probability, input */public function setRate ($ rate = array (12.1, 34) {$ this-> _ rate = $ rate; if (array_sum ($ this-> _ rate)> 100) // check whether the probability is set to throw new Exception ('Winning rate upto 100 '); if (array_sum ($ this-> _ rate) <100) // Defines the probability of a non-winning event. The probability given by the user is only 100 hours, ignore 0 $ this-> _ rate [] = 100-array_sum ($ this-> _ rate);}/** to randomly generate an integer seed from 1, submitted to the winning judgment function * @ return int, sorted by input probability, return the number of winning items */public function runOnce () {return $ this-> judge (mt_rand (0, 10000);}/** determines whether an Input random value wins the prize Based on the set probability * @ param int, a random number less than $ seed 10000 * @ return int, $ I is sorted by input probability and returns the number of items that won the prize */protected function judge ($ seed) {foreach ($ this-> _ rate as $ key => $ value) {$ tmpArr [$ key + 1] = $ val Ue * 100;} // accumulate the probability after 10 for random selection and combination into $ tmpArr [0] = 0; foreach ($ tmpArr as $ key => $ value) {if ($ key> 0) {$ tmpArr [$ key] + = $ tmpArr [$ key-1] ;}} for ($ I = 1; $ I <count ($ tmpArr); $ I ++) {if ($ tmpArr [$ I-1] <$ seed & $ seed <= $ tmpArr [$ I]) {return $ I; // return the number of items (in the probability Setting Order) }}}$ rate = array (33, 20, 2, 0.95, 12, 4.55 ); $ a = new Lottery; $ a-> setRate ($ rate); for ($ I = 0; $ I <= 10000; $ I ++) {$ B = $ a-> runOnce (); @ $ rewar Ds [$ B] ++;} unset ($ rewards ['']); echo array_sum ($ rewards);?> <Html>
PS: here we will provide you with two online tools with similar functions for your reference:
Online random number/string generation tool:
Http://tools.jb51.net/aideddesign/suijishu
High-strength Password generator:
Http://tools.jb51.net/password/CreateStrongPassword