【问题标题】:PHP - Generate a random 5 digit number with a exception from an arrayPHP - 从数组中生成一个随机的 5 位数字,但有一个例外
【发布时间】:2013-01-26 12:03:54
【问题描述】:

我想为文件名生成一个随机的 5 位数字,但有例外。
如果 PHP 将生成例如数字 65,我想设置为 00065(只有 5 位)。
我有一个包含生成器异常的数组:
$uploaded_files= array(00178, 49856, 32183, 02004, 01585);
数组中是已经存在的文件名,数字生成器非常重要,忽略它们,以避免可能的错误。
谢谢。

【问题讨论】:

    标签: arrays exception random numbers generator


    【解决方案1】:

    考虑不要re-invent the wheel,尤其是当您的语言在one wayanother 中可用时。话虽这么说:

    /**
     * Get random number outside an exception list
     *
     * @param array $exception Exception list
     */
    function getRandom($exception=array('00001', '00002', '00003', '00004', '00005')) {
        $rand=str_pad(mt_rand(0,10),5,0,STR_PAD_LEFT);
        if(in_array($rand,$exception))return getRandom($exception);
        return $rand;
    }
    
    var_dump(
        getRandom(),
        getRandom(),
        getRandom(),
        getRandom(),
        getRandom(),
        getRandom()
    );
    

    请注意,这种实现在碰撞速度非常快时会非常昂贵,尤其是在异常列表增长的情况下。

    【讨论】:

    • 你重新发明轮子让我笑了,但你是对的。感谢您提供 getRandom 功能!
    【解决方案2】:

    试试这个:

    //create a rand_value initially
    while(in_array($rand_value, $uploaded_files) {
        $rand_value = rand(0, 99999);
        $rand_value = sprintf("%05s", $rand_value);
    }
    

    【讨论】:

    • <?php $uploaded_files= array(01, 02, 03, 04, 05); $rand_value = rand(0, 15); $rand_value = sprintf("%02s", $rand_value); if (in_array($rand_value,$uploaded_files)){ echo 'Initial random-value: '.$rand_value.'<br>'; echo 'Regenerated random-value: '; $rand_value = rand(0,15); $rand_value = sprintf("%02s", $rand_value); } else{ } echo $rand_value; ?> 如果in_array 中的 PHP 会生成一个 rand 并检查谁在数组中,我该怎么办?请检查代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 2012-10-17
    • 2011-08-09
    • 2020-11-19
    • 2011-06-26
    • 2018-04-03
    相关资源
    最近更新 更多