Home > Backend Development > PHP Tutorial > How to use PHP to randomly extract a specified number of subsets from an array

How to use PHP to randomly extract a specified number of subsets from an array

little bottle
Release: 2023-04-06 08:58:01
forward
3008 people have browsed it

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(&#39;你&#39;, &#39;看&#39;, &#39;我&#39;, &#39;哪&#39;, &#39;里&#39;, &#39;像&#39;, &#39;好&#39;, &#39;人&#39;);
  $_count_random = &#39;3&#39;;
  print_r(rand_arr_from_array($_arr_str, $_count_random));
Copy after login

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!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template