Red envelope sending function, when we enter the number and total amount of red envelopes, PHP will randomly allocate each amount based on these two values to ensure that everyone can receive a red envelope. The amount of each red envelope varies, which is the requirement The amount of red envelopes should be different, and the total amount of all red envelopes should be equal to the total amount.
PHP Ajax has many functions that use it. Today, the editor has implemented a red envelope grabbing function using PHP Ajax. Let's take a look at an example of a PHP Ajax mobile phone program for sending red envelopes, as shown below.
PHP basic process of sending red envelopes: After entering the number and total amount of red envelopes, PHP will randomly allocate each amount based on these two values to ensure that everyone can receive a red envelope, and each red envelope The amount varies. That is to say, the amount of red envelopes received by each person must be different, and the total amount of all red envelopes is equal to the total amount.
Principle of how to send red envelopes in php:
Set the total amount to 10 yuan, and N people will receive it randomly:
N=1 The first
Then the amount of the red envelope = red envelopes=10-the amount of the first red envelope;
N=3 The third
red envelope1=a random number between 0.01 and 9.99
red envelope2=0.01 to (10-red envelope1- 0.01) a random number
红包3=10-红包1-红包2
……
So we get a rule, when allocating the current red envelope amount, reserve the remaining red and white first The minimum amount required, and then take a random number between 0.01 and the total amount - the reserved amount. The random number obtained is the amount of the current red envelope distribution.
jquery code:
$(function() { $("button").click(function() { $.ajax({ type: 'POST', url: 'bao.php', dataType: 'json', beforeSend: function() { $("#result").html('正在分配红包'); }, success: function(json) { if (json.msg == 1) { var str = ''; var res = json.res; $.each(res, function(index, array) { str = '<p>第<span>' array['i'] '</span>个红包, 金额<span>' array['money'] '</span>元,余额<span>' array['total'] '元</span></p>'; }); $("#result").html(str); } else { $("#result").html('数据出错!'); } } }); }); });
PHP code: bao.php
$total=20;//红包总金额 $num=10;// 分成10个红包,支持10人随机领取 $min=0.01;//每个人最少能收到0.01元 for ($i=1;$i<$num;$i ) { $safe_total=($total-($num-$i)*$min)/($num-$i);//随机安全上限 $money=mt_rand($min*100,$safe_total*100)/100; $total=$total-$money; echo '第'.$i.'个红包:'.$money.' 元,余额:'.$total.' 元 '; } echo '第'.$num.'个红包:'.$total.' 元,余额:0 元';
The effect is as shown in the picture:
Method to intercept mixed Chinese and English strings
ThinkPHP5 verification The specific use of the processor
JSON In PHP, the method of deserializing a Json string into an object/array
The above is the detailed content of How to use php combined with ajax to send red envelopes on mobile phone. For more information, please follow other related articles on the PHP Chinese website!