/**
* 拼手气红包金额生成
* @param $money_total红包总金额
* @param $num红包个数
* @return $rand_money_arr每个红包的金额
*/
function red_distribution($money_total,$num){
$rand_arr = [];
for($i=0; $i<$num; $i++) {
$rand = rand(1, 100);
$rand_arr[] = $rand;
}
$rand_sum = array_sum($rand_arr);
$rand_money_arr = array();
$rand_money_arr = array_pad($rand_money_arr, $num, 0.01); //保证每个红包至少0.01
foreach ($rand_arr as $key => $r) {
$rand_money = number_format($money_total*$r/$rand_sum, 2);
if($rand_money <= 0.01 || number_format(array_sum($rand_money_arr), 2) >= number_format($money_total, 2)) {
$rand_money_arr[$key] = 0.01;
} else {
$rand_money_arr[$key] = (float)$rand_money;
}
}
$max_index = $max_rand = 0;
foreach ($rand_money_arr as $key => $rm) {
if($rm > $max_rand) {
$max_rand = $rm;
$max_index = $key;
}
}
unset($rand_money_arr[$max_index]);
//这里的array_sum($rand_money_arr)一定是小于$money_total的
$rand_money_arr[$max_index] = (float)number_format($money_total - array_sum($rand_money_arr), 2);
ksort($rand_money_arr);
return $rand_money_arr;
}
亲测可用,并稍作修改,将数据类型转换为float,原先数据部分为float部分为string