在PHP中随机选择一个数组
问题描述:
我有一个数组,其值类似于1、5、6、9、11、45、56等.我试图做的是随机分配一个值,也许是6.然后我想选择一个随机值值不包括6(因此不能加倍).然后是一个随机值,不包括最后两个,全部来自数组内部.有什么帮助吗?我正在尝试不使用while
循环来执行此操作,但是如果有必要,那就这样吧.
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.
答
我建议以下内容:
# 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]);
请参阅: array_rand , 查看更多