cre*_*ivz 13 php arrays random
从阵列
$my_array = array('a','b','c','d','e');
Run Code Online (Sandbox Code Playgroud)
我想得到两个不同的随机元素.
使用以下代码:
for ($i=0; $i<2; $i++) {
$random = array_rand($my_array); # one random array element number
$get_it = $my_array[$random]; # get the letter from the array
echo $get_it;
}
Run Code Online (Sandbox Code Playgroud)
它可以得到两次相同的字母.我需要阻止这一点.我想总是得到两个不同的数组元素.有人可以告诉我该怎么做吗?谢谢
Vol*_*erK 17
array_rand()可以采用两个参数,即数组和要选择的(不同)元素的数量.
mixed array_rand(array $ input [,int $ num_req = 1])
$my_array = array('a','b','c','d','e');
foreach( array_rand($my_array, 2) as $key ) {
echo $my_array[$key];
}
Run Code Online (Sandbox Code Playgroud)
那这个呢?
$random = $my_array; // make a copy of the array
shuffle($random); // randomize the order
echo array_pop($random); // take the last element and remove it
echo array_pop($random); // s.a.
Run Code Online (Sandbox Code Playgroud)
您可以随时删除第一次选择的元素,然后再不会选择它.如果您不想修改数组,请创建副本.
for ($i=0; $i<2; $i++) {
$random = array_rand($my_array); # one random array element number
$get_it = $my_array[$random]; # get the letter from the array
echo $get_it;
unset($my_array[$random]);
}
Run Code Online (Sandbox Code Playgroud)