gpt4 book ai didi

php - 如何在 PHP 中创建逐渐增加的 PIN?

转载 作者:行者123 更新时间:2023-12-02 15:50:56 25 4
gpt4 key购买 nike

我目前正在开发一个项目,生成随机 PIN 码。最初,每个 PIN 码都以 4 位数字开头,即 2345、5456 等。然而,我试图做到这一点,如果使用了所有 4 位数字引脚,则它会增加到 5 位数字,然后是 6 位等等。本质上,这样您就不会用完!

我正在使用 laravel 并创建了一个特征:

<?php

namespace App\Traits;

use App\Models\Quiz;

trait QuizPinTrait
{
private $pin = null;
private $min, $max;

private function setup()
{
$this->min = 1111;
$this->max = 9999;
$this->pin = mt_rand($this->min, $this->max);
}

public function generate()
{
$this->setup();
if ($this->checkNotInUse()) {
return $this->pin;
}

return false;
}

private function checkNotInUse()
{
$inUse = Quiz::where('pin', $this->pin)->count();

if (!$inUse || $inUse == 0) {
return true;
} else {
// stuck here...
}
}
}

我首先考虑将 1 附加到最小值,将 9 附加到最大值,但我不确定如何为此制定有效的解决方案。

最佳答案

您可以创建一个整数数组,[1111,...,9999],并根据正在使用的 PIN 数组进行比较,以获取可用的 PIN。

$isUse = Quiz:all()->pluck('pin');
$min = 1111;
$max = 9999;
$allPins = range($min,$max);
$notInUse = array_diff($allPins, $inUse);


// laravel one liner
$notInUse = collect(Quiz:all()->pluck('pin'))->diff(range($min,$max));

然后当当前范围没有更多可用时:

$min = $max+1;
$max *= 10;

关于php - 如何在 PHP 中创建逐渐增加的 PIN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48374626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com