开发者

Weekly shuffle of array

开发者 https://www.devze.com 2023-04-06 07:29 出处:网络
I have a set of 4 HTML list items and I\'d like to shuffle the order they appear in once a week. I was wondering if anyone out there had a nice, elegant solution to this?

I have a set of 4 HTML list items and I'd like to shuffle the order they appear in once a week. I was wondering if anyone out there had a nice, elegant solution to this?

As always, I'd be enormously grateful for any input you might have!

UPDATE:

Unfortunately, even with the necessary .htaccess overrides, I just can't get any srand() based solutions to work on this particular server sadly, but have the following which could be used instead - at the moment, it only returns one list item - how could I modify it to show the four required? Once again, any ideas would be gratefully received :)

function RandomList($TimeBase, $QuotesArray){

    $TimeBase = intval($TimeBase);

    $ItemCount = count($QuotesArray);

    $RandomIndexPos = ($TimeBase % $ItemCount);

    return $QuotesArray[$RandomIndexPos];

}

$WeekOfTheYear = date('W'); 

$RandomItems = array(
    "<li><a href=\"#northern-germany\" title=\"Northern Germany\">North</a></li>","<li><a href=\"#southern-germany\" title=\"Southern Germany\">South</a></li>","<li><a href=\"#west开发者_如何学编程ern-germany\" title=\"Western Germany\">West</a></li>","<li><a href=\"#eastern-germany\" title=\"Eastern Germany\">East</a></li>");

print RandomList($WeekOfTheYear, $RandomItems);


Here is a simple and - I guess - pretty elegant solution, which does not involve storing values in a database, setting up cronjobs and other boring stuff of the like.

Let's pretend you have your list elements in $array:

srand(date('W'));
shuffle($array);
srand();

Now your array is shuffled, and will be shuffled the same way until next Monday.

This has a problem, though: it does not work with the Suhosin patch (installed by default in Debian). Still, now that you know about date('W') it will be easy to come up with an alternate solution yourself.

EDIT: if you don't want to implement your own pseudorandom number generator but you have Suhosin installed, you can put the following line in your .htaccess:

php_value suhosin.srand.ignore 0

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号