打印相同的数组值,并每5分钟随机化一次

时间:2014-03-08 08:16:52

标签: php html arrays random

我制作了这段代码,每当你运行它时,它会从数组中回送5个随机数据行。

我真正想要的是它需要数组的5个随机值,并在它再次随机化之前回显相同的值5分钟。

我知道只有将信息存储在MySQL中才有可能,但我更喜欢更简单/更简单的方式。如果只使用PHP,那就太好了。

$random = $id; // make a copy of the multi-dimensional array

for($i = 0; $i < 5; $i++) {
    shuffle($random); // randomize order
    $results = array_pop($random); // return last value and remove from array

    echo $result[0][0], " ", $result[0][1], "<br>\n";
}

有想法或建议的人吗?

5 个答案:

答案 0 :(得分:2)

以下是使用mt_srand()mt_rand()array_multisort()的实施方案。使用array_multisort(),您可以根据另一个数组的值对数组进行排序。

使用每5分钟更改一次的种子,您可以使用mt_rand()创建一个在指定时间内保持不变的'order'数组,您可以使用该数组对目标值进行一致排序,直到'order'数组变化

种子时间的当前实现仅基于分钟,您可能希望根据小时/日期等增加此随机性。

// mocking an array of ids
$ids = range(0, 5);

// create and assign a 'seed' value that changes 
// every $duration and assign to mt_srand
// credited: http://stackoverflow.com/a/2480681/312962
$duration = 5;
$mins = date('i', strtotime('now'));
$seed = $mins - ($mins % $duration);

mt_srand($seed);

// use mt_rand to build an 'order by'
// array that will change every $duration
$orderBy = array_map(function() {
    return mt_rand();
}, range(1, count($ids)));

// sort $ids against $orderBy
array_multisort($orderBy, $ids);

// This will yield
var_dump($ids);

这可能会产生如下所示的内容,其顺序只应在传递给mt_srand()的值发生变化时才会更改。

array (size=6)
  0 => int 4
  1 => int 1
  2 => int 0
  3 => int 3
  4 => int 2
  5 => int 5

希望这会有所帮助:)

答案 1 :(得分:0)

您可以使用缓存(使用Pear::Cache_Lite):

<?php
require_once('Cache/Lite.php');
define("YOUR_ID", "Something identifying the cache");

$options = array(
    'cacheDir' => '/tmp/',
    'lifeTime' => 5 * 60 // 5 min
);

$cache = new Cache_Lite($options);

if ($data = $cache->get(YOUR_ID)) {
    echo $data
} else {
    $random = $id; // make a copy of the multi-dimensional array
    $data = "";
    for($i = 0; $i < 5; $i++) {
        shuffle($random); // randomize order
        $results = array_pop($random); // return last value and remove from array

        $data .= $result[0][0], " ", $result[0][1], "<br>\n";
    }
    echo $data;
    $cache->save($data, YOUR_ID);
}

(未经测试)

答案 2 :(得分:0)

您可以将当前代码放入另一个循环并使用php sleep()函数使脚本暂停五分钟。

$random = $id; // make a copy of the multi-dimensional array

$number_of_times_to_run_code = 10;

for($a = 0; $a < $number_of_times_to_run_code; $a++) {


   for($i = 0; $i < 5; $i++) {
   shuffle($random); // randomize order
   $results = array_pop($random); // return last value and remove from array

   echo $result[0][0], " ", $result[0][1], "<br>\n";
   }

// sleep five minutes (240 seconds)
sleep(240);

}

如果您不希望它停止,您可以使用while循环而不是for循环。

答案 3 :(得分:0)

您可以使用基于文件的缓存,而不是使用数据存储。这将检查文件上次修改的时间以及是否大于5分钟前,它会将其随机化。

if( ! file_exists("array.txt")) {
    touch("array.txt");

    $array = [];

    // generate some random data for the array
    for($i = 0; $i != 10; $i++) {
        for($n = 0; $n != 10; $n++) {
            for($m = 0; $m != 10; $m++) {
                $array[$i][$n][$m] = mt_rand();
            }
        }
    }

    file_put_contents("array.txt", serialize($array));
}

// checks when the file was last modified
if(filemtime("array.txt") <= strtotime('5 minutes ago')) {
    $array = unserialize(file_get_contents("array.txt"));
    shuffle($array);
    file_put_contents("array.txt", serialize($array));
}

$array = unserialize(file_get_contents("array.txt"));

for($i = 0; $i < 5; $i++) {
    $result = array_pop($array);
    echo "{$result[0][0]} {$result[0][1]}<br>\n";
}

答案 4 :(得分:0)

另一种方法是将脚本最后运行的时间存储在SESSION变量中。然后算出经过的时间。我提供了一些示例测试代码。目的是脚本始终运行。您只需决定每次运行时要做什么。它不会每5分钟运行一次,但在这种情况下并不重要。如果他们每隔几分钟访问一次,那么你就可以随机查看它。

session_start();

$timeLastRandom = 0; // if no session variable yet.
$timeNow = time();

if (isset($_SESSION['random_last_run'])) {
  $timeLastRandom = $_SESSION['random_last_run'];
}

// check that the interval has elapsed...
if ($timeNow - $timeLastRandom > (5 * 60)) { // run the new code

  $_SESSION['random_last_run'] = $timeNow; // record time last ran...
  echo 'Time elaspsed -- run your code...' . ($timeNow - $timeLastRandom);
}
else {

  echo 'Time elaspsed -- run your old code...' . ($timeNow - $timeLastRandom);
}