cake在 PHP 中生成唯一 id


cakeGenerate unique id In PHP

我想在我的项目中创建唯一的id。我用过这个

$key = md5(microtime().rand());

但是我想像这样创建唯一的id:HPSEMP001等等HPSEMP002HPSEMP003

无法做到这一点,请帮助我我是PHP的新手

您可以为生成随机数创建递归函数,如果数字在数据库中可用,也会在数据库中检查该函数。

在我的示例中,我使用以下代码为客户创建了不同的随机部门代码,

/**
 * Generate Random number and check if it is exist or not
 */
public function checkAndGenerateRandomNumber($customerId) {
    $number = sprintf("%04s", rand(1,9999));
    $response = ClassRegistry::init('Department')->find('first', array('conditions' => array('Department.customer_id' => $customerId, 'Department.code' => $number)));  
    if(isset($response) && !empty($response)) {
        $this->checkAndGenerateRandomNumber($customerId);
    } else {
        return $number;
    }
}

我是初学者,但我已经尝试过并且它有效:

$num = 0;
global $num;
function new_id() {
    global $num;
    return 'HPSEMP' . sprintf("%03d", $num++); 
}

调用函数的示例:

for ($i = 0; $i < 1500; $i++) {
    $new_id = new_id();
    echo "<br>$new_id";
}

输出:

HPSEMP000
HPSEMP001
HPSEMP002
HPSEMP003
.
.
.
HPSEMP997
HPSEMP998
HPSEMP999
HPSEMP1000

或者,如果您想将代码保存在数据库或文件中,我没有尝试过,但它应该可以工作:

function new_id($num) {
        $num++;
        // * Code to save new number value in file or database
        return 'HPSEMP' . sprintf("%03d", $num++); 
    }
// * Code to retrieve id number from file or database and store it to $num
// * $num = previously stored id number
$new_id = new_id($num);