Algorithm for efficient random extraction of specified records from arrays in PHP_PHP Tutorial

WBOY
Release: 2016-07-21 16:12:37
Original
1383 people have browsed it

PHP uses the array array_rand() function to efficiently randomly extract a specified number of records. It can randomly extract records in 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 remove one or more cells from the array

mixed array_rand(array $input[,int $num_req] )

array_rand() is useful when you want to remove one or more random cells from an array. It accepts input as an input array and an optional parameter num_req, which specifies how many cells you want to remove - if not specified, it defaults to 1.

If you only take out one, array_rand() returns the key name of a random unit, otherwise it returns an array containing random key names. This way you can randomly pull out keys and values ​​from the array.

Let’s take a look at a small example:

Copy code The code is as follows:

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 will randomly select the record number in the $list array. If you need to record the content, you only need to output it.

The following is an example of randomly selecting specific records from the database:

Copy code The code is as follows:

$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);
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/313637.htmlTechArticlephp uses the array_rand() function to efficiently randomly extract a specified number of records, and can randomly extract records from the database , suitable for random display and lottery procedures. The algorithm is mainly...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!