這篇文章主要介紹了PHP 生成微信紅包代碼簡(jiǎn)單的相關(guān)資料,需要的朋友可以參考下
一切解釋盡在代碼中,具體代碼如下所示:
/**
* @param $total [你要發(fā)的紅包總額]
* @param int $num [發(fā)幾個(gè)]
* @return array[生成紅包金額]
*/
function getRedGift($total, $num = 10)
{
$min = 0.01;
$wamp = array();
$returnData = array();
for ($i = 1; $i < $num; ++$i) {
$safe_total = ($total - ($num - $i) * $min) / ($num - $i); //紅包金額的最大值
if ($safe_total < 0) break;
$money = @mt_rand($min * 100, $safe_total * 100) / 100;//隨機(jī)產(chǎn)生一個(gè)紅包金額
$total = $total - $money;//剩余紅包總額
$wamp[$i] = round($money, 2);//保留兩位有效數(shù)字
}
$wamp[$i] = round($total, 2);
$returnData['MoneySum'] = $wamp;
$returnData['newTotal'] = array_sum($wamp);
return $returnData;
}
//測(cè)試
$data = getRedGift(100, 10);
print_r($data);
//result:
/*
Array
(
[1] => 8.7
[2] => 10.09
[3] => 6.23
[4] => 6.87
[5] => 0.47
[6] => 3.12
[7] => 7.52
[8] => 12.21
[9] => 20.53
[10] => 24.26
)*/
代碼到此就給大家寫完了,希望對(duì)大家有所幫助