I have an array that has values like 1, 5, 6, 9, 11, 45, 56, etc. What I'm trying to do is to randomly one value, perhaps 6. Then I want to pick a random value excluding 6 (so no doubles). Then a random value excluding the last two, all from inside an array. Any help? I'm trying to do this without while
loops but if they are necessary then so be it.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
I suggest the following:
# pick a random key in your array
$rand_key = array_rand($your_array);
# extract the corresponding value
$rand_value = $your_array[$rand_key];
# remove the key-value pair from the array
unset($your_array[$rand_key]);
See: array_rand, unset.
回答2:
Shuffle the array first and then use it as a stack:
$a = array(1, 5, 6, 9, 11, 45, 56);
shuffle($a);
// now you can have your picks:
$pick = array_pop($a);
$pick = array_pop($a);
$pick = array_pop($a);
$pick = array_pop($a);
...
回答3:
I would probably shuffle the array and get the first/last x value