This article mainly introduces the method of PHP function shuffle() to get several random elements from an array. It analyzes the function, definition, usage and related precautions of the shuffle function in detail in the form of examples. Friends in need can refer to it
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 the shuffle() function that comes with PHP. Here is 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()
shuffle() function The elements in are rearranged 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 is 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 to randomly extract values from the array: array_rand(), its calling format is as follows: array_rand (array, the number of extracted elements); Of course, to support two-dimensional arrays, it needs to be encapsulated before use. But the previous program supports two-dimensional arrays very well.
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
PHP MVC framework skymvc supports multiple file upload implementation methods
PHP obtains form data and HTML embedding Implementation of PHP script
PHP method to realize paging display of data and simple example
The above is the detailed content of Method and example analysis of PHP function shuffle() to take several random elements from an array. For more information, please follow other related articles on the PHP Chinese website!