仿微信红包,PHP实现发送红包功能

/**
 *
 * @todo 生成红包
 * @return array 红包数组
 * @param $total float 红包总金额
 * @param $num  int 红包个数,默认最小3个
 * @param $min  float 最小金额
 * @author blvming
 */
function genarate_hongbao($total,$num=3,$min=1) {

	$origin_money = $total;

	$hongbao_arr = array();

	if($total<$num){

		return false;

	}

	//保证最少每个人都能得到红包

	$least_money = $total-$num;

	if($least_money<0){

		return false; 

	}elseif($least_money>=0){

		$total = $least_money;

		for($i = 1; $i < $num; $i++) {
			$safe_total = ($total - ($num - $i) * $min) / ($num - $i); // 随机安全上限

			if($safe_total<1){
				$hongbao_arr[$i] = 0;
			}else{
				$money = mt_rand ( $min , $safe_total  ) ;
				// 		$money = mt_rand ( $min * $origin_money, $safe_total * $origin_money ) / $origin_money;
				$total = $total - $money;

				$hongbao_arr[$i] = $money;
			}
		}

		$hongbao_arr[$num] = $total;

		//对每个数组值都+1

		foreach ($hongbao_arr as $k=>$v){
			$hongbao_arr[$k]++;
		}

		shuffle($hongbao_arr);

	}

	return $hongbao_arr;

}
分享到QQ空间

Comments are closed.