用随机种子PHP数组? [英] Randomize a PHP array with a seed?

查看:189
本文介绍了用随机种子PHP数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找我可以在PHP传递一个数组和一个种子,并得到一个随机阵列功能。如果我再次通过相同的阵列和相同的种子,我会得到相同的输出。

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.

我已经试过这code

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?

答案至今与PHP 5.1和5.3的工作,但不是5.2。只是恰巧我想上使用5.2运行此机器。

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.

谁能给不使用mt_rand一个例子吗?因为它不会给基于相同的种子的随机数相同的序列是在PHP 5.2破。请参阅 PHP mt_rand页和的 bug跟踪系统了解这个问题。

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.

推荐答案

您可以使用 在array_multisort 通过 mt_rand 的第二阵列值责令数组值:

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);

下面 $为了 mt_rand 长度相同的值的数组 $ ARR 在array_multisort 排序 $为了的价值和订单 $改编 $秩序的值的顺序

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆