php從數組中隨機抽取一些元素代碼大家可參考一下.
實例代碼如下:
- <?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 ); // 從小到大排序,根據需要修改
- return $getArray;
- }
- }
- //測試代碼
- $keywords = array(
- "我們",
- "你們",
- "他們"
- );
- $getValue=new getValues();
- $getValue->inputValue($keywords);
- $key = $getValue->getValue(1);//從數組中隨機抽取一個元素
- ?>
新聞熱點
疑難解答