随机取出一维数组中的N个元素 PHP

<?php

	$testArr = range(a, z);

	#######  the first method  

	$newArr = arrayRand($testArr);

	var_dump($newArr);

	function arrayRand($arr, $num = 3) {
		$arr1 = array_rand($arr, $num);

		$newArr = array();

		foreach ($arr1 as $key => $value) {
			$newArr[] = $arr[$value];
		}

		return $newArr;
	}
	echo "\n";


	######  the second method

	$arr2 = arrayRandom($testArr);

	var_dump($arr2);



	function arrayRandom($arr, $num = 3) {
		shuffle($arr);

		// list($a, $b, $c) = $arr;

		$newArr = array();

		for ($i = 0; $i < $num; $i++) {
			$newArr[] = $arr[$i];
		}

		return $newArr;
	}



	###### the third method    getting random value from assoc arrays

	$testArr = array(
		'a' => 'siyuantlw',
		'b' => 'chengxusheji',
		'c' => 'redisfans',
		'd' => 'phpzl',
		'e' => 'yemiansheji'
	);

	echo "\n";

	$newArr = assocArrayRandom($testArr);

	var_dump($newArr);

	function assocArrayRandom($arr, $num = 2) {
		$keyArr = array_keys($arr);

		shuffle($keyArr);

		$newArr = array();

		for ($i = 0; $i < $num; $i++) {
			$newArr[$keyArr[$i]] = $arr[$keyArr[$i]];
		}

		return $newArr;
	}

?>

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注