简体   繁体   English

根据PHP中的字符串在范围内生成固定的随机数

[英]Generate a fixed random number in a range based on a string in PHP

I need to generate a random number or hash that will be the same each time based on a string. 我需要根据字符串生成每次都是相同的随机数或哈希。 This is done easily enough with the function crc32, however, I need it to be an integer between a range because the random number will be picking an item out of an array. 使用函数crc32可以很容易地做到这一点,但是,我需要将它作为一个范围之间的整数,因为随机数将从数组中选择一个项目。

Here's the code I have so far: 这是我到目前为止的代码:

$min=0;
$max=count($myarray);
$number = crc32("Joe Jones");

$rnd = '.'.(string)$number;
//(Int((max-min+1)*Rnd+min))
$rand = round(($max-$min+1)*$rnd+$min);

echo $rand;

It seems to work, but it always picks lower numbers. 似乎可行,但总是选择较低的数字。 It never picks the higher numbers. 它从不选择更高的数字。

Just use mod (%). 只需使用mod (%)。 $x % $n will ensure an output between 0 and $n-1 for any $x . $x % $n将确保任何$x的输出在0$n-1之间。

$myArray=range(1,1000);
$max=count($myArray); //1000
$number = crc32("Joe Jones"); //2559948711
$rand=$number % $max; //711

Also just a note about crc32: It may return a negative number if you run it on a 32 bit platform, so you may optionally want to do abs(crc32($input)) 也仅是关于crc32的注释:如果您在32位平台上运行它,则可能会返回负数,因此您可以选择执行abs(crc32($input))

Your crc32 function is producing a negative number. 您的crc32函数产生一个负数。 Change the line as follows: 更改行,如下所示:

$number = abs(crc32("Joe Jones"));

This turns that negative number in to a positive one. 这会将负数变成正数。 Also, you might want to consider multiplying that number if your your array count is is low. 另外,如果您的阵列数量较少,则可能要考虑将该数字乘以。 How high that goes is up to you. 多高取决于您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM