Help! How to generate a random number more quickly!
The requirement is this:
Member shopping, will generate an order number, this order number must be a number, and is within a certain range of data, such as 1 to 100,000.
I'm using rand (1,100000), generate a random number, get this random number, then go to the database, if already exist this number, then cycle again.
The code is as follows:
Set_time_limit (0);
$test = M (' test ');
$_run = true;
$_order_id = rand (0, 100000);
while ($_run) {
erInfo = $test->where ("val =". $_order_id)->find ();
if (empty (erInfo)) {
$_run = false;
return $_order_id;
}else{
$_order_id = rand (0, 100000);
}
}
In this way, when the order number is very small, it is easy to get the order number, but if the order number has reached 99990
This time, to generate other order numbers will be a long time, a few minutes or even one hours is possible.
This method is not feasible.
Please friends to help think of ways, or provide other ideas, thank you!
------to solve the idea----------------------
You can write a pseudo-random number generator yourself.
First observe
$m = 100000;
$c = 101;
$b = 81;
$n = 0;
for ($i =0; $i <100000; $i + +) {
$n = ($n * $c + $b)% $m;
$r [] = $n;
}
Print_r (Array_count_values (Array_count_values ($r)));
Array
(
[1] = 100000
)
It is known that there are 0-99999 randomly arranged numbers in the $r, and each number only appears once
Make $n the last inbound number, ($n * $c + $b)% $m must not be in the library
I hope you can understand.