php中的伪随机数 [英] Pseudo random numbers in php

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

问题描述

我有一个函数可以根据随机数以不同的顺序输出项目.例如,有 1/2 的时间 Popeye's 和它的将在列表中排名第一,而 Taco Bell 和它的标志将是 #2 和一半的时间\它将是相反的.

I have a function that outputs items in a different order depending on a random number. for example 1/2 of the time Popeye's and its will be #1 on the list and Taco Bell and its logo will be #2 and half the time \it will be the other way around.

问题在于,当用户重新加载或返回页面时,顺序会重新随机化.这里的 $Range 是 db 中的项目数,因此它使用 1 和 $range 之间的随机数.

The problem is that when a user reloads or comes back to the page, the order is re-randomized. $Range here is the number of items in the db, so it's using a random number between 1 and the $range.

  $random = mt_rand(1,$range);
  for ($i = 0 ; $i < count($variants); $i++) {
    $random -= $variants[$i]['weight'];
    if ($random <= 0) {
      $chosenoffers[$tag] = $variants[$i];
      break;
    }
  }

我去了会话的开头并设置了这个:

I went to the beginning of the session and set this:

if (!isset($_SESSION['rannum'])){
    $_SESSION['rannum']=rand(1,100);
    }

我的想法是,我可以用某种伪随机生成器替换函数中的 mt_rand,该生成器在整个会话中使用相同的 1-100 随机数作为种子.这样我就不必重写所有已经编写的代码.我是在吠错树还是这是个好主意?

With the idea that I could replace the mt_rand in the function with some sort of pseudo random generator that used the same 1-100 random number as a seed throughout the session. That way i won't have to rewrite all the code that was already written. Am I barking up the wrong tree or is this a good idea?

推荐答案

工作应该是:

<?php
srand(1);
echo rand();
// 1804289383
srand(1);
echo rand();
// 1804289383
?>

或各自

<?php
mt_srand(1);
echo mt_rand(1, 100);
//58
mt_srand(1);
echo mt_rand(1, 100);
//58
?>

并像您说的那样在会话中保存种子

and saveing the seed in the session like you said

这篇关于php中的伪随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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