PHP 数组中取出随机取出指定数量子值集

#关键:array_rand() 函数返回数组中的随机键名,或者如果您规定函数返回不只一个键名,则返回包含随机键名的数组。
#思路:先使用array_rand()随机取出所需数量键名,然后将这些键名指向的值重新组合为数组
 1   /**
 2    * 数组中取出随机取出指定数量子值集
 3    * @param $array array
 4    * @param $count int
 5    * @return array
 6    */
 7   function rand_arr_from_array($array, $count)
 8   {
 9     !is_int($count) && $count = intval($count);
10 
11     if ($count < 0) return false;
12 
13     $_arr_return = array();
14 
15     if ($count >= count($array)) {
16       $_arr_return = $array;
17     } else if ($count > 0) {
18       $temp = array_rand($array, $count);//随机返回指定数量键值 $count > 1 返回键值数组,$count = 1 返回键值字符串,
19 
20       if ($count == 1) $temp = array($temp);
21 
22       //重组数组
23       foreach ($temp as $val) $_arr_return[] = $array[$val];
24     }
25 
26     return $_arr_return;
27   }
28 
29   $_arr_str = array('你', '看', '我', '哪', '里', '像', '好', '人');
30   $_count_random = '3';
31   print_r(rand_arr_from_array($_arr_str, $_count_random));

posted on 2018-12-03 09:16  你看我哪里像好人  阅读(1958)  评论(0编辑  收藏  举报

导航