php 根據自增id建立唯一編號類的方法

來源:互聯網
上載者:User
本文主要介紹了php根據自增id建立唯一編號類的相關知識。具有很好的參考價值。下面跟著小編一起來看下吧

在開發過程中,我們資料表一般都使用自增數字作為id主鍵,而id是數字型,不容易理解。我們把id按一定格式轉為編號後,很容易根據編號知道代表的是什麼內容。

例如訂單表id=20160111197681234,只看id我們並不知道這個id是訂單表的id,而轉為編號O-20160111197681234,則很容易看出是訂單表的記錄,然後可以根據id在訂單表中搜尋。

編號建立的規則

1.唯一

使用自增id產生,保證唯一性

2.儘可能短

可使用數字求餘對應字母的方式處理,建立較短的編號

演算法原理

1.加自訂首碼,用於標識

2.格式使用首碼+字母+數字組成,數字只保留N位,超過的使用數字求餘的方式使用字母對應

例如:

id=1

首碼=F

數字保留3位

則建立的編號為:F-A-001

代碼如下:

IDCode.class.PHP

<?php/** * php 根據自增id建立唯一編號類 * Date:  2016-11-27 * Author: fdipzone * Ver:   1.0 * * Func * Public create 建立編號 */class IDCode{ // class start  /**   * 建立編號   * @param Int  $id     自增id   * @param Int  $num_length 數字最大位元   * @param String $prefix   首碼   * @return String   */  public static function create($id, $num_length, $prefix){    // 基數    $base = pow(10, $num_length);    // 產生字母部分    $pision = (int)($id/$base);    $word = '';    while($pision){      $tmp = fmod($pision, 26); // 只使用26個大寫字母      $tmp = chr($tmp + 65);   // 轉為字母      $word .= $tmp;      $pision = floor($pision/26);    }    if($word==''){      $word = chr(65);    }    // 產生數字部分    $mod = $id % $base;    $digital = str_pad($mod, $num_length, 0, STR_PAD_LEFT);    $code = sprintf('%s-%s-%s', $prefix, $word, $digital);    return $code;  }} // class end?>

demo.php

<?phprequire 'IDCode.class.php';$test_ids = array(1,9,10,99,100,999,1000,1009,2099,3999,9999,14999,99999);foreach($test_ids as $test_id){  echo $test_id.' = '.IDCode::create($test_id, 3, 'F').'<br>';}?>

輸出:

1 = F-A-0019 = F-A-00910 = F-A-01099 = F-A-099100 = F-A-100999 = F-A-9991000 = F-B-0001009 = F-B-0092099 = F-C-0993999 = F-D-9999999 = F-J-99914999 = F-O-99999999 = F-VD-999

以上就是本文的全部內容,希望對大家的學習有所協助。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.