我有一个函数可用于为唯一键生成随机哈希,我设置了要使用的数字序列(generateRecordLocatorID(13,6,11);
),它将生成一个诸如873e874704-e3bf859b86-fe2c1dcad9
之类的键。我想保留这种模式,但是想稍微简化一下此功能-想法?
private function generateRecordLocatorID($n1,$n2,$n3) {
$seed = str_split(md5(rand(0000000,9999999)));
$rand = array_rand($seed, $n1);
$convert = array_map(function($n) use ($seed){
return $seed[$n];
},$rand);
$var1 = implode('',$convert);
$seed = str_split(md5(rand(0000000,9999999)));
$rand = array_rand($seed, $n2);
$convert = array_map(function($n) use ($seed){
return $seed[$n];
},$rand);
$var2 = implode('',$convert);
$seed = str_split(md5(rand(0000000,9999999)));
$rand = array_rand($seed, $n3);
$convert = array_map(function($n) use ($seed){
return $seed[$n];
},$rand);
$var3 = implode('',$convert);
$NewAPI = $var1 . '-' . $var2 . '-' . $var3;
return $NewAPI;
}
答案 0 :(得分:2)
测试此代码,可以正常工作:
private function generateRecordLocatorID($n1,$n2,$n3) {
$nums = [$n1, $n2, $n3];
$newNums = array_map(function($n) {
return substr(md5(microtime()),rand(0,31-$n),$n);
}, $nums);
return implode('-', $newNums);
}
答案 1 :(得分:1)
您的意思是这样吗?未经测试。
private function generateRecordLocatorID1($n1,$n2,$n3) {
$var1 = generateOne($n1);
$var1 = generateOne($n2);
$var1 = generateOne($n3);
$NewAPI = $var1 . '-' . $var2 . '-' . $var3;
return $NewAPI;
}
private function generateOne($n){
$seed = str_split(md5(rand(0000000,9999999)));
$rand = array_rand($seed, $n2);
$convert = array_map(function($n) use ($seed){
return $seed[$n];
},$rand);
return implode('',$convert);
}
答案 2 :(得分:1)
只要有重复的代码,就应该将其重构为如下功能:
private function generateRecordLocatorID($n1,$n2,$n3) {
$var1 = locatorIDPart($n1);
$var2 = locatorIDPart($n2);
$var3 = locatorIDPart($n3);
$NewAPI = $var1 . '-' . $var2 . '-' . $var3;
return $NewAPI;
}
private function locatorIDPart($nx) {
$seed = str_split(md5(rand(0000000,9999999)));
$rand = array_rand($seed, $nx);
$convert = array_map(function($n) use ($seed){
return $seed[$n];
},$rand);
$var = implode('',$convert);
return $var;
}
如果您想继续进行更多的重构,我将提出一些不必要的任务,像这样
private function generateRecordLocatorID($n1,$n2,$n3) {
return locatorIDPart($n1). '-' . locatorIDPart($n2) .'-'. locatorIDPart($n3);
}
private function locatorIDPart($nx) {
$rand = array_rand(str_split(md5(rand(0000000,9999999))), $nx);
$convert = array_map(function($n) use ($seed){
return $seed[$n];
},$rand);
return implode('',$convert);
}
答案 3 :(得分:0)
简短而通用的答案(可以使用任意数量的参数调用):
function generateRecordLocatorID() {
return implode('-', array_map(function($n) {
return substr(md5(microtime()),rand(0,31-$n),$n);
}, func_get_args())
);
};
有趣的方式:
function generateRecordLocatorID($n1,$n2,$n3) {
$n = $n1+$n2+$n3+2;
$str = substr(md5(microtime()),rand(0,31-$n),$n);
$str[$n1] = '-';
$str[$n1+$n2+1] = '-';
return $str;
};