dqnqpqv3841 2018-07-04 08:27
浏览 51
已采纳

如何在php中编写带前缀的唯一优惠券代码

I am trying to write prefixed unique coupon code for get the chance to be a intern at one company. It went well so far, my code is generating 250st, 10 length of codes every time I refresh the page. However, I am issuing a problem with prefixed part. Normally coupon code is looking like this, just one example "1SC476XY3B" but I want every code to start "AB" and then 8 length of code so total will be 10. Can you help me guys? All help will be appreciated, thanks.

<?php

function unique_coupon_codes($number_of_codes,$exclude_codes_array='',$code_length = 10)
{

$characters = "0123456789QWERTYUIOPASDFGHJKLZXCVBNM";

$unique_codes = array();
for($j = 1 ; $j <= $number_of_codes; $j++)
{
    $code = "";
    for ($i = 1; $i <= $code_length; $i++)
    {
        $code .= $characters[mt_rand(0, strlen($characters)-1)];
    }

    if(!in_array($code,$unique_codes))
    {
        if(is_array($exclude_codes_array))
        {
            if(!in_array($code,$exclude_codes_array))
            {
                $unique_codes[$j] = $code;
            }
            else
            {
                $j--;
            }
        }
        else
        {
            $unique_codes[$j] = $code;
        }
    }
    else
    {
        $j--;
    }
}
return $unique_codes;
}

echo '<h1>Unique Coupon Codes</h1>';
echo '<pre>';
print_r(unique_coupon_codes(250,'',10));
echo '</pre>';
  • 写回答

2条回答 默认 最新

  • doulianglou0898 2018-07-04 08:34
    关注

    It needs a minor change while initializing $code variable. Change $code = ""; to $code = "AB"; And call unique_coupon_codes function as

    print_r(unique_coupon_codes(250, '', 8));
    

    Here generate a unique code of 8 digits as you already have prefix AB of length 2 characters.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里