This article is an introduction to how to use PHP to randomly extract a specified number of subsets from an array. It has certain reference value. Friends in need can take a look.
#Key: The array_rand() function returns a random key in an array, or an array containing random keys if you specify that the function returns more than one key.
#Idea: First use array_rand() to randomly retrieve the required number of key names, and then recombine the values pointed to by these key names into an array
/** * 数组中取出随机取出指定数量子值集 * @param $array array * @param $count int * @return array */ function rand_arr_from_array($array, $count) { !is_int($count) && $count = intval($count); if ($count < 0) return false; $_arr_return = array(); if ($count >= count($array)) { $_arr_return = $array; } else if ($count > 0) { $temp = array_rand($array, $count);//随机返回指定数量键值 $count > 1 返回键值数组,$count = 1 返回键值字符串, if ($count == 1) $temp = array($temp); //重组数组 foreach ($temp as $val) $_arr_return[] = $array[$val]; } return $_arr_return; } $_arr_str = array('你', '看', '我', '哪', '里', '像', '好', '人'); $_count_random = '3'; print_r(rand_arr_from_array($_arr_str, $_count_random));
Related tutorials: PHP video tutorial
The above is the detailed content of How to use PHP to randomly extract a specified number of subsets from an array. For more information, please follow other related articles on the PHP Chinese website!