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 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器