簡體   English   中英

在PHP中生成唯一ID

[英]Generate 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM