/** * 拼手氣紅包金額生成 * @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部分爲stringphp