doulezhi5326 2017-02-16 14:49
浏览 32

如何改进这个随机促销代码生成器脚本? [重复]

This question already has an answer here:

I have this script that generates random promo codes.

    }
    $length = 10;
    $characters = '123456789ABCDEFGHJKMNPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $event = $request->event;
    $prefix = $request->prefix;
    $quantity = $request->quantity;
    $randomString = '';
    for ($x = 0; $x <= $quantity; $x++) {
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }

        $pin = "$prefix"."$randomString";
        $exists = Pin::where('pin', $pin)->first();
        if(!$exists){
            $new['pin'] = $pin;
            $new['event'] = $event;
            $new['user'] = '';
            Pin::create($new);
        }

        $randomString = '';
    }

It works but needs to be optimized as it can take forever to execute when the $quantity gets above a couple thousand.

I suspect the time hog is the bit that is looking if the pin exists. I am sure there must be a more efficient way to ensure the random strings are unique.

Thoughts? Thanks!

****** As pointed out random hash generation has been addressed here ******

Perhaps a part 2 to this question then...

Client has requested a set selection of chars for the random codes - '123456789ABCDEFGHJKMNPQRSTUVWXYZ'. Is there a way to limit the chars output by md5 hash?

</div>
  • 写回答

1条回答 默认 最新

  • dtrovwl75780 2017-02-16 14:51
    关注

    A much simpler way:

    $randomString = sha1(rand(0, 2000));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题