php 自增,php 根据自增id创建唯一编号类
在開(kāi)發(fā)過(guò)程中,我們數(shù)據(jù)表一般都使用自增數(shù)字作為id主鍵,而id是數(shù)字型,不容易理解。我們把id按一定格式轉(zhuǎn)為編號(hào)后,很容易根據(jù)編號(hào)知道代表的是什么內(nèi)容。
例如訂單表id=20160111197681234,只看id我們并不知道這個(gè)id是訂單表的id,而轉(zhuǎn)為編號(hào)O-20160111197681234,則很容易看出是訂單表的記錄,然后可以根據(jù)id在訂單表中搜尋。
編號(hào)創(chuàng)建的規(guī)則
1.唯一
使用自增id生成,保證唯一性
2.盡可能短
可使用數(shù)字求余對(duì)應(yīng)字母的方式處理,創(chuàng)建較短的編號(hào)
算法原理
1.加自定義前綴,用于標(biāo)識(shí)
2.格式使用前綴+字母+數(shù)字組成,數(shù)字只保留N位,超過(guò)的使用數(shù)字求余的方式使用字母對(duì)應(yīng)
例如:
id=1
前綴=F
數(shù)字保留3位
則創(chuàng)建的編號(hào)為:F-A-001
代碼如下:
IDCode.class.PHP<?php /** * php 根據(jù)自增id創(chuàng)建唯一編號(hào)類(lèi) * Date: 2016-11-27 * Author: fdipzone * Ver: 1.0 * * Func * Public create 創(chuàng)建編號(hào) */class IDCode{ // class start /** * 創(chuàng)建編號(hào) * @param Int $id 自增id * @param Int $num_length 數(shù)字最大位數(shù) * @param String $prefix 前綴 * @return String */ public static function create($id, $num_length, $prefix){ // 基數(shù) $base = pow(10, $num_length); // 生成字母部分 $division = (int)($id/$base); $word = ""; while($division){ $tmp = fmod($division, 26); // 只使用26個(gè)大寫(xiě)字母 $tmp = chr($tmp + 65); // 轉(zhuǎn)為字母 $word .= $tmp; $division = floor($division/26); } if($word==""){ $word = chr(65); } // 生成數(shù)字部分 $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")."
";}?>
輸出: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
源碼下載地址:點(diǎn)擊查看
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持網(wǎng)頁(yè)設(shè)計(jì)!
總結(jié)
以上是生活随笔為你收集整理的php 自增,php 根据自增id创建唯一编号类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: php this 代表什么,php中$t
- 下一篇: php委托模式,PHP设计模式 - 委托