Home > Backend Development > PHP Tutorial > Randomly extract some elements from a PHP array_PHP tutorial

Randomly extract some elements from a PHP array_PHP tutorial

WBOY
Release: 2016-07-13 17:16:02
Original
1175 people have browsed it

The function of randomly extracting some elements is very simple. Just use array_rand and range. If you randomly select an element, just use mt_rand and grow it into a random number whose length does not exceed the array length.

I will provide you with several methods below for your reference.


Method-:

print_r($arr1);
The code is as follows
 代码如下 复制代码

$arr = range(1,10,1);
   
$newarr = array_rand($arr,6);    //随机获取6个数组中的键
   
$newArr = array_flip($newarr);   //键与值互换
   
$arr3 = array_diff_key($arr,$newArr); //取键相同的
   
$arr1 = array_diff_key($arr,$arr3);  //取键相同的
   
print_r($arr1);

Copy code

$arr = range(1,10,1);

 
 代码如下 复制代码

$arr = range(1,10,1);
   
$newarr = array_rand($arr,6);    //随机获取6个数组中的键
   
$ArrNew = array();
   
foreach($newarr as $k=>$v)

   $ArrNew[$v] = $arr[$v];    
}
   
print_r($ArrNew);

$newarr = array_rand($arr,6); // Randomly obtain the keys in 6 arrays

 

$newArr = array_flip($newarr); //Key and value interchange

 

$arr3 = array_diff_key($arr,$newArr); //Get the ones with the same key
 代码如下 复制代码

$arr = range(1,10,1);
  
shuffle($arr);   //打乱数组
  
$newarr = array_splice($arr,0,6);
  
print_r($newarr);

 

$arr1 = array_diff_key($arr,$arr3); //Get the ones with the same key

 

Result: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [5] => 6 [9] => 10 ) Method 2:
The code is as follows Copy code
$arr = range(1,10,1);   $newarr = array_rand($arr,6); //Randomly obtain the keys in 6 arrays   $ArrNew = array();   foreach($newarr as $k=>$v) { $ArrNew[$v] = $arr[$v];
}
  print_r($ArrNew); Result:Array ( [1] => 2 [2] => 3 [3] => 4 [4] => 5 [6] => 7 [7] => 8 ) Method 3: This method does not retain the key name, for your reference.
The code is as follows Copy code
$arr = range(1,10,1); shuffle($arr); //Shuffle the array $newarr = array_splice($arr,0,6); print_r($newarr); Result:Array ( [0] => 7 [1] => 4 [2] => 2 [3] => 10 [4] => 9 [5] => 6 ) http://www.bkjia.com/PHPjc/628721.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628721.htmlTechArticleThe method of randomly extracting some elements is very simple. You only need to use array_rand and range. If you randomly extract Just use mt_rand directly for an element and then grow it into a random number...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template