php生成随机红包

/**
     *   
     * @param $packet_total 红包总额 
     * @param $packet_count 红包个数 
     * @param $packet_max 每个小红包的最大额 
     * @param $packet_min 每个小红包的最小额 
     * @return 存放生成的每个小红包的值的一维数组 
     */
    public function getpacket() {

        $father_toal = $packet_total = input('packet_total');
        $packet_count = input('packet_count');
        $middle = $packet_count/2;   //用于判断用那种方法发红包
        //当已经分配了半数后最小值用$packet_min
        $packet_min = ($packet_total/$packet_count)*0.1;
        //当已经分配了小于半数时最小值用$packet_min1
        $packet_min1 = ($packet_total/$packet_count)*0.5;
        if($packet_min<0.01 && $packet_min1<0.01){
            return json_encode(array('status'=>0,'msg'=>"金额太少,红包数太多,小气鬼!"));
        }
        $n = $packet_count;
        for ($i = 0; $i < $packet_count - 1; $i++) {
            if($i <= $middle){
                $safe_total1 = (($packet_total - ($packet_count - $i) * $packet_min1) / ($packet_count - $i))*5; //随机安全上限  
                $money = mt_rand($packet_min1 * 100, $safe_total1 * 100) / 100;
                if($money<=0){
                    echo "hello";break;
                }
                $result[] = round($money,2);
                $packet_total = $packet_total - $money;
            }else{
                $safe_total = ($packet_total - ($packet_count - $i) * $packet_min) / ($packet_count - $i); //随机安全上限  
                $money = mt_rand($packet_min * 100, $safe_total * 100) / 100;
                if($money<=0){
                    $money = 0.01;
                }
                $result[] = $money;
                $packet_total = $packet_total - $money;
            }
            
        }
        
        $left_money = $father_toal - array_sum($result);
        $result[] = $left_money;
         
        return json_encode($result);

    }

猜你喜欢

转载自blog.csdn.net/sluckyboy/article/details/81701492
今日推荐