Php Algorithm for efficient random extraction of specified records through Arrays

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.