【问题标题】:Print same values of an array, and randomize it every 5 minutes打印数组的相同值,并每 5 分钟随机化一次
【发布时间】:2014-04-11 14:12:22
【问题描述】:

我编写了这段代码,每次运行时它都会从数组中回显 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";
}

谁有想法或建议?

【问题讨论】:

标签: php html arrays random


【解决方案1】:

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

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

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

// 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

希望这会有所帮助:)

【讨论】:

  • 我喜欢你的回答。但是,您的代码的一个问题是,尽管将持续时间设置为 5,但它仍然每 1 分钟更新一次。你能解决这个问题吗?
  • 傻我!匆忙中我犯了一个错误——我没有用正确的值播种mt_srand()。已更新,对此感到抱歉。
【解决方案2】:

你可以使用缓存(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);
}

(未测试)

【讨论】:

    【解决方案3】:

    您可以将当前代码放到另一个循环中,并使用 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 循环。

    【讨论】:

    • 我需要它停下来。否则我无法为用户加载我的完整网站。
    【解决方案4】:

    您可以使用基于文件的缓存,而不是使用数据存储。这会检查文件最后一次修改的时间,如果超过 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";
    }
    

    【讨论】:

      【解决方案5】:

      另一种方法是将脚本上次运行的时间存储在 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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-10
        • 2020-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 1970-01-01
        相关资源
        最近更新 更多