Php uses the array array_rand () function to efficiently and randomly extract a specified number of records. It can randomly extract records from the database and is suitable for random display and lottery programs.
This algorithm mainly uses the array_rand () function of php. Let's take a look at the main functions of the array_rand () function:
Array_rand-randomly retrieve one or more units from the array
Mixed array_rand (array $ input [, int $ num_req])
Array_rand () is useful when you want to extract one or more random units from an array. It accepts input as an input array and an optional parameter num_req, specifying the number of units you want to retrieve-if not specified, the default value is 1.
If you only retrieve one key, array_rand () returns the key name of a random unit. Otherwise, an array containing the random key name is returned. In this way, you can randomly retrieve the key name and value from the array.
Below is a small example:
Copy codeThe Code is as follows:
<? Php
Srand (float) microtime () * 10000000 );
$ Input = array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank ");
$ Rand_keys = array_rand ($ input, 2 );
Print $ input [$ rand_keys [0]. "\ n ";
Print $ input [$ rand_keys [1]. "\ n ";
?>
This function randomly extracts the record number from the $ list array. You only need to output the record content.
The following is an example of randomly extracting a specific record from a database:
Copy codeThe Code is as follows:
<? Php
$ List = $ DB-> where ("status = 1 and flag = 1")-> order ('sort ')-> select ();
Unset ($ Case );
$ Count = count ($ list );
$ Rand_list = range (0, $ count-1 );
$ Rand_list = array_rand ($ rand_list, 10 );
$ Tuijian_array = array ();
Foreach ($ rand_list as $ key ){
$ Tuijian_array [] = $ list [$ key];
}
Unset ($ case_list );
Print_r ($ tuijian_array );
?>