Php creates a unique id Class Based on the auto-increment id, and phpid creates a number
In the development process, we usually use auto-increment numbers as the id Primary Key for data tables, and id is a numeric type, which is not easy to understand. After converting IDS into numbers in a certain format, it is easy to know what the IDS represent.
For example, order table id =20160111197681234We do not know that this id is the id of the Order table.O-20160111197681234It is easy to see that it is the order table record, and then you can search in the order table by id.
Rule created by ID
1. Unique
Use auto-incremental id generation to ensure uniqueness
2. As short as possible
You can use numbers to obtain the remainder of the corresponding letter to create a shorter number.
Algorithm principle
1. Add a custom prefix for identification
2. The format is composed of a prefix, letters, and numbers. Only N digits are retained. If the number exceeds the limit, a letter is used to calculate the remainder.
For example:
Id = 1
Prefix = F
Number reserved 3 bits
The created ID is:F-A-001
The Code is as follows:
IDCode. class. PHP
<? Php/*** php creates a unique id Class Based on the auto-increment id * Date: * Author: fdipzone * Ver: 1.0 ** Func * Public create creation Number */class IDCode {// class start/*** creation Number * @ param Int $ id auto-increment id * @ param Int $ num_length number maximum number of digits * @ param String $ prefix * @ return String */public static function create ($ id, $ num_length, $ prefix) {// base $ base = pow (10, $ num_length); // generate the letter section $ division = (int) ($ id/$ base ); $ word = ''; while ( $ Division) {$ tmp = fmod ($ division, 26); // use only 26 uppercase letters $ tmp = chr ($ tmp + 65 ); // convert to $ word. = $ tmp; $ division = floor ($ division/26);} if ($ word = '') {$ word = chr (65 );} // generate the number section $ mod = $ id % $ base; $ digital = str_pad ($ mod, $ num_length, 0, STR_PAD_LEFT ); $ code = sprintf ('% 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>';}?>
Output:
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
Source code: Click to view
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!