php is the code for randomly selecting elements from an array

  • 2020-05-27 04:29:02
  • OfStack

 
<?php 
class getValues { 
public function inputValue($inputArray) { 
$this->inputArray = $inputArray; 
} 
public function getValue($number) { 
$this->number = $number; 
for($i = 0; $i < $this->number; $i ++) { 
$index = rand ( 0, count ( $this->inputArray ) - 1 - $i ); 
$getArray [$i] = $this->inputArray [$index]; 
unset ( $this->inputArray [$index] ); 
for($k = $index; $k < count ( $this->inputArray ) - 1; $k ++) { 
$this->inputArray [$k] = $this->inputArray [$k + 1]; 
} 
} 
//asort ( $getArray ); //  Sort from small to large, and modify as needed  
return $getArray; 
} 
} 

// The test code  
$keywords = array( 
" we ", 
" you ", 
" they " 
); 
$getValue=new getValues(); 
$getValue->inputValue($keywords); 
$key = $getValue->getValue(1);// It's randomly drawn from the array 1 An element  
echo $key; 
 ? > 

Related articles: