Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php // http://stackoverflow.com/questions/34180258/generate-and-save-million-of-uniques-codes/34183586#34183586
- /**
- * This creates a database connction and initializes an ORM.
- * I use redbeanPHP but Doctrine can also be used
- */
- include __DIR__ . '/__bootstrap__.php';
- use pip\system\encryption\RandomData;
- use pip\system\ElapsedTiming;
- \R::freeze(true); // table already exists - make it faster.
- define('BATCH_ID_MIN', 100);
- define('BATCH_ID_MAX', 999);
- define('BATCH_ID_CNT', 2); // 100 really
- define('BATCH_ID_MAX_TRIES', 50000); // should be less than this ;-/
- define('BATCH_MIN', 0);
- define('BATCH_MAX', 999999999);
- define('BATCH_CNT', 100); // Ten thousand really
- define('BATCH_MAX_TRIES', 999999999); // should be a less than this ;-/
- // generate all the batch ids
- $batchIds = makeBatch(BATCH_ID_MIN, BATCH_ID_MAX, BATCH_ID_CNT, BATCH_ID_MAX_TRIES);
- // for each batch id generate all the unique 9 digit numbers
- foreach(array_keys($batchIds) as $id) {
- // takes approx 2 seconds per batch
- $batchNos = makeBatch(BATCH_MIN, BATCH_MAX, BATCH_CNT, BATCH_MAX_TRIES);
- // takes approx 30 seconds per 10000 batch - this can be improved :)
- saveBatch($id, array_keys($batchNos));
- }
- // Show output...
- $results = \R::getAll('select batchid, batchno from batchbean
- order by batchid, batchno', array());
- foreach ($results as $number) {
- echo 'Random: ', sprintf('%3d-%9d', $number['batchid'], $number['batchno']), PHP_EOL;
- }
- exit();
- // due to the low chance of collision then this doesn't need stats - whatever - collect them
- function makeBatch($batchMin, $batchMax, $required, $maxTries = BATCH_MAX_TRIES)
- {
- $rand = new RandomData();
- $batchIds = array();
- $created = 0;
- while ($created < $required && $maxTries > 0) {
- $batchId = $rand->int32($batchMin, $batchMax);
- $maxTries--;
- if (isset($batchIds[$batchId])) {
- $batchIds[$batchId]++;
- continue;
- }
- $batchIds[$batchId] = 1;
- $created++;
- }
- $GLOBALS['maxTries'] = $maxTries;
- ksort($batchIds);
- return $batchIds;
- }
- /**
- * Insert each batch into a database table.
- *
- * I use RedbeanPHP so it does all the work for me but will be a little slow
- */
- function saveBatch($batchId, $batchNumbers)
- {
- \R::begin();
- foreach($batchNumbers as $batchNo) {
- $bean = \R::dispense('batchbean');
- $bean->batchid = $batchId;
- $bean->batchno = $batchNo;
- \R::store($bean);
- }
- \R::commit();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement