This article describes the PHP random lottery usage. Share to everyone for your reference. The specific analysis is as follows:
1. According to the set probability, get the result of the random lottery.
Copy Code code as follows:
<?php
/**
* Lottery Tools
*/
Class Lottery_tool {
protected static $AWARDSARR;
protected static $proField = ' probability ';
protected static $proSum = 0;
protected static $checkAward = false;
Const SUCCESS_CODE = 0;
Const FAIL_CODE =-1;
Check Lottery data
protected static function Checkawards () {
if (!is_array self:: $AWARDSARR) | | Empty (self:: $AWARDSARR)) {
Return self:: $checkAward = false;
}
Self:: $proSum = 0;
foreach (self:: $AWARDSARR as $_key => $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 isn't ' 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 probability field name
public static function Setprofield ($field = null) {
if (!empty ($field)) {
Self:: $proField = $field;
}
}
Set up Prizes
public static function Setawards ($awards) {
Self:: $AWARDSARR = $awards;
Self::checkawards ();
}
}
2. Sample code:
Copy Code code as follows:
$awards = Array (
' 0 ' => array (' Pro ' =>, ' info ' => ' 15% possibilities '),
' 1 ' => array (' Pro ' =>, ' info ' => ' 25% possibilities '),
' 2 ' => array (' Pro ' =>, ' info ' => ' 40% possibilities '),
' 3 ' => array (' Pro ' =>, ' info ' => ' 20% possibilities '),
);
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 ' <pre> ';
Var_dump ($awards);
The results of the operation are as follows:
Copy Code code as follows:
Array
0 =>
Array
' Pro ' => int 15
' Info ' => string ' 15% probability ' (length=15)
' num ' => int 1596
1 =>
Array
' Pro ' => int 25
' Info ' => string ' 25% probability ' (length=15)
' num ' => int 2484
2 =>
Array
' Pro ' => int 40
' Info ' => string ' 40% probability ' (length=15)
' num ' => int 3939
3 =>
Array
' Pro ' => int 20
' Info ' => string ' 20% probability ' (length=15)
' num ' => int 1981
I hope this article will help you with your PHP program design.