The basic flow of red envelopes in PHP: When the amount of red envelopes and the total amount of input, PHP will be based on these two values to randomly allocate each amount, to ensure that everyone can receive a red envelope, and the amount of each red envelopes vary. That is, the amount of red envelopes each person receives is different, and the total amount of all red envelopes equals the total amount. As shown in figure:
PHP Red Envelopes To achieve the principle:
Set the total amount of 10 yuan, there are n individuals to collect randomly:
N=1 First
The red envelope amount =x yuan;
N=2 a second
To ensure that the second red envelope can be issued normally, the first red envelope amount = a random number between 0.01 and 9.99
The second red envelope =10-the first red envelope amount;
N=3 a third.
A random number between red envelopes 1=0.01 to 9.99
A random number of red envelopes 2=0.01 to (10-red envelope 1-0.01)
Red Envelopes 3=10-Red Envelopes 1-Red Envelopes 2
......
So we get a rule, in allocating the current red envelope amount, first reserve the remaining red and white required the minimum amount, and then in 0.01 to the total amount-reserve amount between the random number, the resulting random number is the current amount of red envelopes allocated.
In practical application, the program will first allocate the amount of red envelopes, that is, when the red envelopes, the number of red envelopes and the amount of each red packets are allocated, then the user to rob red envelopes, we randomly return a red envelope to the user.
jquery Code:
$ (function () {
$ ("button"). Click (function () {
$.ajax ({
Type: ' POST ',
URL: ' bao.php ',
DataType: ' JSON ',
Beforesend:function () {
$ ("#result"). html (' Distributing red envelopes ');
},
Success:function (JSON) {
if (json.msg = = 1) {
var str = ';
var res = json.res;
$.each (Res,
function (index, array) {
str = ' <p> <span> ' + array[' i '] + ' </span> a red envelope,
Amount <span> ' + array[' money '] + ' </span> yuan, balance <span> ' +
array[' total '] + ' yuan </span></p> ';
});
$ ("#result"). html (str);
} else {
$ ("#result"). HTML (' data Error! ');
}
}
});
});
});
PHP Code: bao.php
$total =20;//Red Envelope Total amount
$num =10;//is divided into 10 red envelopes, supporting 10 people to pick up randomly
$min =0.01;// Each person receives at least 0.01 yuan
for ($i =1 $i < $num; $i + +)
{ & nbsp
$safe _total= ($total-($num-$i) * $min)/($num-$i);//random security upper bound
$money =mt_rand ($min *100, $safe _total*100)/100;
$total = $total-$ money;
Echo ' $i. ' A red envelope: '. $money. ' Yuan, Balance: '. $ Total. ' Yuan ';
}
Echo ' $num. ' A red envelope: '. $total. ' Yuan, balance: 0 yuan ';