I came across a great problem the other day and wanted to share results here. The problem scenario was that I had a group of objects, and I wanted to show a random entry from the group. The caveat however, was that I wanted to the random entry to be the same for the period of one hour.
In essence I wanted to perform an array_rand in php, but with a custom and static seed for the random number generator.
The solution was to use an array map while overriding the random number generator using mt_srand. Then use array_multisort to sort our array according to our array map.
Here is the full block of code:
Here it is as text so that it can be copied:
mt_srand(date('G',time()); $order = array_map(create_function('$value', 'return mt_rand();'), range(1, count($objects))); array_multisort($order, $objects); $object = array_shift($objects);
Now let’s look at this a little closer.
First we set up the current hour (00-23) to use as our seed into the better random number generator: http://us3.php.net/manual/en/function.mt-srand.php
Next we create a range based upon our size of objects… We put that range into an array_map to create an array called order, which will represent the order to use.
$order = array_map(create_function('$value', 'return mt_rand();'), range(1, count($objects)));
Then we pass the $order array and the array of objects into the array_multisort function to have them sorted the exact same way.
At this point we could return the sorted array of objects. Or in our case we wanted to grab 1 entry, we will return the first element in the array.
$object = array_shift($objects);
Hope that helps!