The example in this article describes the method of PHP function shuffle() to get several random elements from an array. Share it with everyone for your reference, the details are as follows:
Sometimes we need to take several random elements in the array (such as making random recommendation functions), so how to implement it in PHP? A relatively simple solution is to use PHP's own shuffle() function. Here’s a simple example:
$data[] = array( "name" => "帮客之家", "rank" => "40" ); $data[] = array( "name" => "博客园", "rank" => "50" ); $data[] = array( "name" => "CSDN", "rank" => "60" ); $data[] = array( "name" => "ITEYE", "rank" => "50" ); shuffle($data); $i = 0; foreach($data as $key =>$value ){ if($i < 2) { echo $data[$key]['name'].'<br />'; } $i++; }
shuffle()
The shuffle() function rearranges the elements in the array in random order. Returns TRUE if successful, FALSE otherwise. This function assigns new keys to the elements in the array. This will delete the original keys rather than just reorder them.
If an associative array is passed in, you will find that the key names of the associative array will be lost. By the way, here’s the solution:
// 打乱关联数组的排序 function shuffle_assoc($array) { $randomized_keys = array_rand($array, count($array)); foreach($randomized_keys as $current_key) { $output[$current_key] = $array[$current_key]; } return $output; }
In addition, PHP also provides a function for randomly extracting values from an array: array_rand(). Its calling format is as follows: array_rand (array, the number of extracted elements); Of course, to support two-dimensional arrays, encapsulation is also required. It can be used immediately. But the previous program supports two-dimensional arrays very well.
Readers who are interested in more PHP-related content can check out the special topics on this site: "Summary of PHP operations and operator usage", "Summary of PHP network programming skills", "Introduction to PHP basic syntax", "php operation office documentation" Summary of skills (including word, excel, access, ppt)", "Summary of php date and time usage", "Introduction to php object-oriented programming tutorial", "Summary of php string (string) usage", "Introduction to php mysql database operation" Tutorial" and "Summary of Common PHP Database Operation Skills"
I hope this article will be helpful to everyone in PHP programming.