Results 1 to 3 of 3

Thread: PHP Array Question

  1. #1
    retrograde
    Guest

    PHP Array Question

    Okay, I'm trying to figure out how to do something in PHP. Hopefully, I can explain clearly what I'm trying to do and one of you out there could help me.

    I have an array with, lets say, 300 or so elements. I want to randomize the elements every day. That would be easy enough just by using shuffle().

    However, I want the randomization to be based on the date. For example, on August 17th, I want all the elements randomized the same way, and for August 18th I want them to be randomized the same way.

    What would be the best way to handle this?

    [Actually, now that I think about it, to randomize such a large array upon every page load would probably be very CPU intensive. Any ideas?]


  2. #2
    retrograde
    Guest
    Well, actually... I think I *may* have solved my first question.

    Here's the code I'm using. It's a slightly modified version of one posted by users on php.net.

    PHP Code:
    function swapshuffle($testing) {
       
    srand ((double) date("Ymd") * 10000000);
       for (
    $i=0;$i<sizeof($testing);$i++) {
           
    $from=rand(0,sizeof($testing)-1);
           
    $old=$testing[$i];
           
    $testing[$i]=$testing[$from];
           
    $testing[$from]=$old;
       }
    return 
    $testing

    Sure enough, this randomizes the array in such a way that it remains the same. Now I just have to make sure that it'll change when the day changes.


  3. #3
    JustMe
    Guest

    Re: PHP Array Question

    Greetings:

    Originally posted by retrograde
    [Actually, now that I think about it, to randomize such a large array upon every page load would probably be very CPU intensive. Any ideas?]
    You're absolutely right, this would not be designing a site with performance in mind. You won't notice much if the site doesn't get a lot of traffic, but if you get the hits, or plan on getting them, this is not the way to go. It might even be a big problem from the start, depending on what the elements in this array are, and how they're being called up in the first place.

    The best thing to do, would be to have the elements in a database (again, I'm not exactly sure what we're randomizing here). Then, you can have the elements of that database arranged once a day by a small script that gets called up via cron. The script would sort the array, and update the database to reflect the position of each element. This way, the sorting only takes place once a day, instead of once each time your page is visited. The resulting sort would be stored in the database as I've mentioned, then it's just a simple matter of calling it in your php script.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •