Random Unique 6 digit number generation in CI3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | public function generateCoupon($numCoupons = 32500) { // Define allowed characters for alphabet and digits $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $digits = '0123456789'; $alphaLength = strlen($alphabet); $digitLength = strlen($digits); // Coupon amount distribution $amountDistribution = [ 500 => 2000, // 2000 coupons with amount 500 200 => 5000, // 5000 coupons with amount 200 100 => 7000, // 7000 coupons with amount 100 50 => 18500 // 18500 coupons with amount 50 ]; // Prepare the data for batch insert $insertData = []; $couponCount = 0; $coupons = []; // Loop through each amount distribution foreach ($amountDistribution as $amount => $count) { for ($i = 0; $i < $count; $i++) { // Generate a unique coupon code in the format AAA111 $couponCode = ''; while (true) { // First 3 characters: Alphabetical $couponCode = ''; for ($j = 0; $j < 3; $j++) { $couponCode .= $alphabet[rand(0, $alphaLength - 1)]; } // Last 3 characters: Numeric for ($k = 0; $k < 3; $k++) { $couponCode .= $digits[rand(0, $digitLength - 1)]; } // Check if the coupon code is unique if (!in_array($couponCode, $coupons)) { // Add unique coupon to the list and exit while loop $coupons[] = $couponCode; break; } } // Prepare data for batch insert $insertData[] = [ 'coupon' => $couponCode, 'amount' => $amount, 'expire_date' => date('Y-m-d'), // Set expire_date to today's date 'status' => 1 ]; $couponCount++; // Optional: Break early for testing purposes if ($couponCount >= $numCoupons) { break 2; // Break out of both loops } } } // Insert coupons in batches (chunk size of 500 or smaller to avoid memory issues) $chunks = array_chunk($insertData, 500); foreach ($chunks as $chunk) { $this->db->insert_batch('coupon', $chunk); // Insert the current chunk } echo count($insertData); // Return the number of coupons inserted } |