生成规则设计

每一个电子商务网站,现在有一种或多种类型的优惠/折扣/优惠券系统,给大家分享一下如何在PHP生成唯一的促销/折扣码

<?php
/** 
 * @param int $no_of_codes//定义一个int类型的参数 用来确定生成多少个优惠码
 * @param array $exclude_codes_array//定义一个exclude_codes_array类型的数组
 * @param int $code_length //定义一个code_length的参数来确定优惠码的长度
 * @return array//返回数组
 */
function generate_promotion_code($no_of_codes, $exclude_codes_array = '', $code_length = 4) {
    $characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $promotion_codes = array(); //这个数组用来接收生成的优惠码
    for ($j = 0; $j < $no_of_codes; $j++) {
        $code = "";
        for ($i = 0; $i < $code_length; $i++) {
            $code.= $characters[mt_rand(0, strlen($characters) - 1) ];
        }
        //如果生成的4位随机数不再我们定义的$promotion_codes函数里面
        if (!in_array($code, $promotion_codes)) {
            if (is_array($exclude_codes_array)) //
            {
                if (!in_array($code, $exclude_codes_array)) //排除已经使用的优惠码
                {
                    $promotion_codes[$j] = $code;
                    #将生成的新优惠码赋值给promotion_codes数组
                } else {
                    $j--;
                }
            } else {
                $promotion_codes[$j] = $code; //将优惠码赋值给数组               
            }
        } else {
            $j--;
        }
    }
    return $promotion_codes;
}
echo '<h1>Promotion / Discount Codes</h1>';
echo '<pre>';
print_r(generate_promotion_code(50, '', 4));
echo '</pre>';
?> 

discuz 卡密生成规则设计:DZ2011QSYLP54985V6Q9T

public static function buildFormatRand($format, $number = 1, $except_array = []) {
    $rand_list = array();
    $length = strlen($format);
    for ($j = 0; $j < $number; $j++) {
        $rand_string = '';
        for ($i = 0; $i < $length; $i++) {
            $char = substr($format, $i, 1);
            switch ($char) {
                case "*": //字母和数字混合
                    $rand_string .= self::random(1, 'FULL');
                    break;
                case "#": //数字
                    $rand_string .= self::random(1, "NUM");
                    break;
                case "@": //大写字母
                    $rand_string .= self::random(1, "ENGLISH");
                    break;
                default: //其他格式均不转换
                    $rand_string .= $char;
                    break;
            }
        }
        if (!in_array($rand_string, $rand_list)) {
            if (count($except_array)) {
                if (!in_array($rand_string, $except_array)) {
                    $rand_list[] = $rand_string;
                } else {
                    $j--;
                }
            } else {
                $rand_list[] = $rand_string;
            }
        } else {
            $j--;
        }
    }
    return $number == 1 ? $rand_string : $rand_list;
}

 

 

猜你喜欢

转载自hudeyong926.iteye.com/blog/1860360