Think about, write your own PHP version of the red envelope random generation algorithm, can achieve similar functions (in fact, dare not say is the algorithm).
//$bonus _totalTotal amount of red envelopes
//$bonus _countNumber of red envelopes
//$bonus _typeRed Envelope Type 1 = spell Lucky Red packet 0 = normal Red envelope
function Randbonus ($bonus _total=0, $bonus _count=3, $bonus _type=1) { $bonus _items = Array ();//results to be divided $ Bonus_balance = $bonus _total; Balance after each split $bonus _avg = Number_format ($bonus _total/$bonus _count, 2);//The average amount of each red envelope $i = 0; while ($i < $bonus _count) { if ($i < $bonus _count-1) { $rand = $bonus _type? ( Rand (1, $bonus _balance*100-1)/100): $bonus _avg; Calculates the amount of the current red envelope based on the type of red envelope $bonus _items[] = $rand; $bonus _balance-= $rand; } else{ $bonus _items[] = $bonus _balance;//The last red packet is contracted directly to the final amount, guaranteeing that the total amount issued is correct } $i + +; } return $bonus _items;}
Well, let's try it now.
Send 3 Lucky Red envelopes, the total amount is 100 yuan $bonus_items = Randbonus (100, 3, 1);//View the generated red envelopes var_dump ($bonus _items);//Check the total amount is not correct, See if there's a hole in our money Var_dump (array_sum ($bonus _items));
Another version that uses an array implementation is similar in principle:
function Sendrandbonus ($total =0, $count =3, $type =1) { if ($type ==1) { $input = range (0.01, $total, 0.01); if ($count >1) { $rand _keys = (array) array_rand ($input, $count-1); $last = 0; foreach ($rand _keys as $i = + $key) { $current = $input [$key]-$last; $items [] = $current; $last = $input [$key]; } } $items [] = $total-array_sum ($items); } else{ $avg = Number_format ($total/$count, 2); $i = 0; while ($i < $count) { $items [] = $i < $count-1? $avg:(-array_sum ($total)); $i + +; } } return $items;}
The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support the script home.