I am wondering if the shuffle() array function is the correct way to randomize array results.
Basically, I have some ad codes in an array, and I use this to display 1 random ad each time, but there is an ad that seems to appear much much more than anything! I mean out of 20 times it appeared about 18 times. I'd thought by randomizing the results I'd get around equal views fo开发者_运维百科r each ad but thats not the case.
It makes me question here. Is shuffle the correct way to do this.. or do I need something totally different?
Here is my code to grab the random ad code at a time.
if (count($eligible_ads) > 1) {
shuffle($eligible_ads);
echo stripslashes($eligible_ads[0]['code']);
}
You could also simply pick a random key using array_rand
, instead of shuffling the whole thing. It won't get any more random than that*
. You can't say something's not random with test data based on only 20 runs. It should even out if you run it a few thousand more times.
In other words:
*
As far as PRNGs go at least.
Random means Random. It wouldn't be random if it gave equal views to each ad. shuffle()
randomizes the order of the elements in the array, associative or otherwise. If your goal is to give equal views to each "ad" in the array, then no, shuffle()
is not what your after. You could probably write a function that uses boolean logic to give equal views though.
If you don't mind the hit of running a database query or two, throw the ads into a table, and create a column that will store how many times that ad was displayed. SELECT the row with the MIN(views) ordered by RAND() and increase the view count of the row that was selected. This will ensure every ad is viewed the same number of times, but shown in a random order.
精彩评论