抢红包代码留存

<?php
//phpinfo();
header("Content-type:text/html;charset=utf-8");
include 'Mysql.class.php';
 $redis = new Redis();
 $redis->connect('127.0.0.1', 6379);
 $user_id = $_GET['user_id']?$_GET['user_id']:1;
 $money = $_GET['money'];
 $num = $_GET['num'];

 //创建红包 并进行拆包存入缓存
if($_GET['action'] == "add"){
    
    
    $data = hongbao($money,$num);
    foreach ($data as $key => $value) {
        $redis->lPush("hongbao".$user_id,$value);
    }

    echo "红包创建成功";

    //抢包动作
}elseif($_GET['action'] == "send"){
    $count = $redis->Lsize("hongbao".$user_id);
    $c_user_id = rand();
    if($count>0 && $price = $redis->lPop("hongbao".$user_id)){
        
         $mysql = new Mysql("localhost","root","root","qhb");
         $data = array(
             'user_id'=>$c_user_id,
             'price'=>$price,
         );
         $mysql->insert("hongbao",$data);
        // file_put_contents("./data/hongbao.log", " 抢到红包:金额为:".$data['price']."userid:".$data['user_id'],FILE_APPEND);
    }else{
        // file_put_contents("./data/hongbao.log", " 没有抢到红包,userid:".$c_user_id,FILE_APPEND);
    }
}

/**
     * 红包生成算法
     * @param $money    总金额
     * @param $number   红包数量
     * @param $ratio    浮动系数
     */
    function hongbao($money,$number,$ratio = 0.5){
        $res = array(); //结果数组
        $min = ($money / $number) * (1 - $ratio);   //最小值
        $max = ($money / $number) * (1 + $ratio);   //最大值
        /*--- 第一步:分配低保 ---*/
        for($i=0;$i<$number;$i++){
            $res[$i] = $min;
        }
        $money = $money - $min * $number;
        /*--- 第二步:随机分配 ---*/
        $randRatio = 100;
        $randMax = ($max - $min) * $randRatio;
        for($i=0;$i<$number;$i++){
            //随机分钱
            $randRes = mt_rand(0,$randMax);
            $randRes = $randRes / $randRatio;
            if($money >= $randRes){ //余额充足
                $res[$i]    += $randRes;
                $money      -= $randRes;
            }
            elseif($money > 0){     //余额不足
                $res[$i]    += $money;
                $money      -= $money;
            }
            else{                   //没有余额
                break;
            }
        }
        /*--- 第三步:平均分配上一步剩余 ---*/
        if($money > 0){
            $avg = $money / $number;
            for($i=0;$i<$number;$i++){
                $res[$i] += $avg;
            }
            $money = 0;
        }
        /*--- 第四步:打乱顺序 ---*/
        shuffle($res);
        /*--- 第五步:格式化金额(可选) ---*/
        foreach($res as $k=>$v){
            //两位小数,不四舍五入
            preg_match('/^d+(.d{1,2})?/',$v,$match);
            $match[0]   = number_format($match[0],2);
            $res[$k]    = $match[0];
        }

        return $res;
    }
?>

原文地址:https://www.cnblogs.com/ylcms/p/7345081.html