記錄一次優惠券生成-去重php
方法一數組
/**
* 生成批量禮品消費券
*/
public function giftCardAddOp() {
//接收get值
$num = $_GET['gift_num'];
$branch_prefix = $_GET['city_name'];
if ($_GET) {
$this->add_gift_card($branch_prefix, $num);
}
showMessage('禮品碼生成成功!','index.php?act=order&op=giftCardCode');ui
}
/**
* 處理插入
*$branch_prefix
*$num
*$sum
*
*/
private function add_gift_card($branch_prefix, $num ,$sum='0'){this
// 計數
$n = 0;
$promotion_codes = array();//這個數組用來接收生成的優惠碼
for ($i=0; $i < (($sum >0) ? $sum : $num); $i++) {
$charid = strtoupper(md5(uniqid(mt_rand(), true)));
$uuid = substr($charid, 8, 8);code
$company = '愛之依';
$promotion_codes[$i] = $uuid;
$data.= "('".$branch_prefix."','".$uuid."','".time()."','".$company."'),";md5
//插入一次 +1
$n++;
//防止死循環
$num_con = $num+1000;
if ($n == $num_con) {
break;
}
}
//去除右側逗號
$data = rtrim($data,',');
//批量插入
$model_gift_card = Model('goods_gift_card');
$gift_code_info = $model_gift_card->addGiftAll($data);ci
//若是插入成功true
if ($gift_code_info) {
//查詢插入數量
$condition = array('branch_prefix' => $branch_prefix);
$gift_count = $model_gift_card->getGiftCodeCount($condition);get
//插入失敗的再次循環插入
if ($gift_count < $num) {
$this->add_gift_card($branch_prefix, $num, $num - $gift_count);
}
}it
}io
方法2:
$array = [];
$num = 10;
$lenght = 8;
$start = 99999999;
$step = 60000;
$arrDate = explode('-', date('Y-m-d'));
$m = base_convert($arrDate[1],10,32); //進制轉換
$d = base_convert($arrDate[2],10,32);
for ($i=$start;$i<=($start+$step*$num);$i+=$step){
$array[] = $uuid = strtoupper($m.$d.str_pad(base_convert($i,10,32),$lenght-2,'0',STR_PAD_LEFT)); //取進制數,不足補0
}
var_dump($array);die;
$update['gift_card_code'] = $uuid;
$update['add_time'] = time();
$update['use_time'] = 0;
$update['buyer_id'] = 0;
$update['is_delete'] = 0;
$update['order_id'] = 0;
$model_gift_card = M('goods_gift_card'); $gift_code_info = $model_gift_card->add($update); if(strlen(array_pop($array))>9) return false; return $array;