在应用软件开发中,经常需要生成一种长度一致并且不能重复的字符串序列或者数字编号ID,来保证一条数据记录的唯一性,比如电商平台中的订单编号、会员系统中的邀请码、激活码等等,这里总结一下在PHP中生成唯一序列的几种方法以及他们的用例和注意事项。
function uuid() {
if (function_exists ( 'com_create_guid' )) {
return com_create_guid (); //com_create_guid()是php自带的生成唯一id方法,php5之后好像已经被移除了
} else {
mt_srand ( ( double ) microtime () * 10000 ); //optional for php 4.2.0 and up.随便数播种,4.2.0以后不需要了。
$charid = strtoupper ( md5 ( uniqid ( rand (), true ) ) ); //根据当前时间(微秒计)生成唯一id.
$hyphen = chr ( 45 ); // "-"
$uuid = '' . //chr(123)// "{"
substr ( $charid, 0, 8 ) . $hyphen . substr ( $charid, 8, 4 ) . $hyphen . substr ( $charid, 12, 4 ) . $hyphen . substr ( $charid, 16, 4 ) . $hyphen . substr ( $charid, 20, 12 );
//.chr(125);// "}"
return $uuid;
}
}
function create_guid($namespace = '') {
static $guid = '';
$uid = uniqid("", true);
$data = $namespace;
$data .= $_SERVER['REQUEST_TIME'];
$data .= $_SERVER['HTTP_USER_AGENT'];
$data .= $_SERVER['SERVER_ADDR'];
$data .= $_SERVER['SERVER_PORT'];
$data .= $_SERVER['REMOTE_ADDR'];
$data .= $_SERVER['REMOTE_PORT'];
$hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
$guid = '{' .
substr($hash, 0, 8) .
'-' .
substr($hash, 8, 4) .
'-' .
substr($hash, 12, 4) .
'-' .
substr($hash, 16, 4) .
'-' .
substr($hash, 20, 12) .
'}';
return $guid;
}
date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999); //类似第一种方法
function create_seq() {
$order_id_main = date('YmdHis') . rand(10000000, 99999999);
$order_id_len = strlen($order_id_main);
$order_id_sum = 0;
for ($i = 0; $i < $order_id_len; $i++) {
$order_id_sum += (int)(substr($order_id_main, $i, 1)); //这里对生成的随机序列进行加法运算使重复率降低
}
$nid = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
return $nid;
}
function create_seq() {
$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
$orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
return $orderSn;
}