Home  >  Article  >  Backend Development  >  PHP randomly removes several different numbers from an array

PHP randomly removes several different numbers from an array

PHP中文网
PHP中文网Original
2017-03-30 16:50:031577browse

PHP randomly extracts several different numbers from an array

The first algorithm is other people’s ideas on CSDN

$num = 0; 
 $array = array(1, 2, 3, 4, 5, 6, 7, 8, 9); 
 $arr = array(); 
 $g = 5; 
 $tag = true; 
 while ($tag) { 
   $count = count($array); 
   $t = rand(0, 1); 
   if ($t == 1) { 
     $arr[] = $array[$num]; 
     unset($array[$num]); 
   } 
   $num ++; 
   if (count($arr) == $g) { 
     $tag = false; 
   } 
   if ($num == $count) { 
     $num = 0;  //循环 
   } 
 } 
var_dump($arr);

The second algorithm is my own idea.

You can replace the data with the last unobtained data after each fetching, and then randomly obtain values ​​from the unobtained data

function swap(&$a, &$b) 
{ 
  $temp = $b; 
  $b = $a; 
  $a = $temp; 
} 
   
   
$result = array(); 
$src = array(); 
for($i = 0 ; $i < 40 ; $i++) 
{ 
  $src[] = $i + 1; 
} 
$arr_len = count($src); 
$count = 20; 
$index = 0; 
while($index < $count) 
{ 
  $random = rand(0, $arr_len - $index - 1); 
  $result[] = $src[$random]; 
  swap($src[$random] , $src[$arr_len - $index - 1]); 
  $index += 1; 
} 
   
   
print_r(json_encode($result)); 
print_r(json_encode($src));

The above is how PHP randomly takes out several different values ​​from an array For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement:
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