在PHP中生成唯一id

在PHP中生成唯一id,php,cakephp,Php,Cakephp,我想在我的项目中创建唯一的id。我用过这个 $key = md5(microtime().rand()); 但是我想创建这样的唯一id:HPSEMP001等等HPSEMP002,HPSEMP003 我无法做到这一点,请帮助我我是PHP新手,我是一名初学者,但我尝试过这一点,效果很好: $num = 0; global $num; function new_id() { global $num; return 'HPSEMP' . sprintf("%03d", $num++)

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

$key = md5(microtime().rand());
但是我想创建这样的唯一id:
HPSEMP001
等等
HPSEMP002
HPSEMP003


我无法做到这一点,请帮助我我是PHP新手,我是一名初学者,但我尝试过这一点,效果很好:

$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";
}
或者,如果您希望将代码保存在数据库或文件中,我没有尝试过此方法,但它应该可以工作:

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);

您可以为生成随机数创建递归函数,若数据库中有或并没有随机数,也会在数据库中检查该函数

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

/**
 * 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;
    }
}

我希望每次调用此001002时,它都会返回我在
HPSEMP999
之后的内容。请在db或文件中跟踪生成的id。此外,如果您想要真正唯一的id,请在HPSEMP999之后使用
uniqid()
@AlmaDo此HPSEMP1000
/**
 * 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;
    }
}