用种子随机化一个 PHP 数组? [英] Randomize a PHP array with a seed?
问题描述
我正在寻找一个函数,我可以在 PHP 中将数组和种子传递给它并返回一个随机化"数组.如果我再次传递相同的数组和相同的种子,我会得到相同的输出.
我试过这个代码
<前>//样本数组$test = array(1,2,3,4,5,6);//显示数组打印_r($test);//种子随机数生成器mt_srand('123');//根据它生成一个随机数回声 mt_rand();回声\n";//打乱数组洗牌($测试);//显示结果打印_r($test);但是好像不行.关于做到这一点的最佳方法有什么想法吗?
这个问题围绕这个问题跳舞,但它已经过时了,没有人提供关于如何做的实际答案:我可以通过以下方式随机化一个数组吗?提供种子并获得相同的订单? - 是" - 但如何?
更新
目前的答案适用于 PHP 5.1 和 5.3,但不适用于 5.2.碰巧我想运行它的机器使用的是 5.2.
谁能举一个不使用 mt_rand 的例子?它在 php 5.2 中被破坏"了,因为它不会基于相同的种子给出相同的随机数序列.请参阅 php mt_rand 页面 和 错误跟踪器 以了解此问题.
您可以使用 array_multisort
按第二个 mt_rand
值数组对数组值进行排序:>
$arr = array(1,2,3,4,5,6);mt_srand('123');$order = array_map(create_function('$val', 'return mt_rand();'), range(1, count($arr)));array_multisort($order, $arr);var_dump($arr);
这里的$order
是与$arr
长度相同的mt_rand
值数组.array_multisort
对$order
的值进行排序,并按照$order
的值对$arr
的元素进行排序代码>.
I'm looking for a function that I can pass an array and a seed to in PHP and get back a "randomized" array. If I passed the same array and same seed again, I would get the same output.
I've tried this code
//sample array $test = array(1,2,3,4,5,6); //show the array print_r($test); //seed the random number generator mt_srand('123'); //generate a random number based on that echo mt_rand(); echo "\n"; //shuffle the array shuffle($test); //show the results print_r($test);
But it does not seem to work. Any thoughts on the best way to do this?
This question dances around the issue but it's old and nobody has provided an actual answer on how to do it: Can i randomize an array by providing a seed and get the same order? - "Yes" - but how?
Update
The answers so far work with PHP 5.1 and 5.3, but not 5.2. Just so happens the machine I want to run this on is using 5.2.
Can anyone give an example without using mt_rand? It is "broken" in php 5.2 because it will not give the same sequence of random numbers based off the same seed. See the php mt_rand page and the bug tracker to learn about this issue.
You can use array_multisort
to order the array values by a second array of mt_rand
values:
$arr = array(1,2,3,4,5,6);
mt_srand('123');
$order = array_map(create_function('$val', 'return mt_rand();'), range(1, count($arr)));
array_multisort($order, $arr);
var_dump($arr);
Here $order
is an array of mt_rand
values of the same length as $arr
. array_multisort
sorts the values of $order
and orders the elements of $arr
according to the order of the values of $order
.
这篇关于用种子随机化一个 PHP 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!