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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line