2012-05-20 49 views
0

我創建一個售票系統學習之用,我想知道我將如何創造出有類同這種簡單獨特的票ID:gD8f-jxSPHP票務ID生成

這將有4個字符隨機案在第一部分

(字母和數字是允許的,那麼這將有一個破折號,任何情況下再次3個隨機字母或數字。

+6

你是娶了這種模式呢?因爲這是相當很容易使用'uniqid()'。 –

+0

有點,但如果這樣更容易,我可以使用它,有什麼方法可以縮短它嗎?如果不是,那沒關係。 – unlucky4ever

+0

不,它不能縮短,除非你在它上面串起了manip,這會破壞它的獨特性。搜索此網站以使用PHP生成YouTube ids。製作短標識符的例子很多。 –

回答

4
public function generateCode(){ 

    $unique = FALSE; 
    $length = 7; 
    $chrDb = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'); 

    while (!$unique){ 

      $str = ''; 
      for ($count = 0; $count < $length; $count++){ 

       $chr = $chrDb[rand(0,count($chrDb)-1)]; 

       if (rand(0,1) == 0){ 
       $chr = strtolower($chr); 
       } 
       if (3 == $count){ 
       $str .= '-'; 
       } 
       $str .= $chr; 
      } 

      /* check if unique */ 
      //$existingCode = UNIQUE CHECK GOES HERE 
      if (!$existingCode){ 
      $unique = TRUE; 
      } 
    } 
    return $str; 
}