Possible Duplicate:
Generating random results by weight in PHP?
i have made a database in which i store the name and the link of rss feeds.i have made the rss reader and everything is ok till now.I want to make a news scroller which will show the articles of the feeds.But i want to give to the feeds some weight values in order every feed to be selected according to its importance for me and automatically when a feed is selected from those in the database its articles only will be showed in the scroller.Any ideas of how can i do that???Thanks in advance..
p.s. my problem is how can i do aytomatically the random weighted choice of the feeds from the database and not how to show the articles of the feeds(i have done this part).
You can find fast algorithm implemented and described - weighted random (in javascript but can be rewritten to PHP in a few minutes I think). It is much faster than loop through the array.
Two ways to do this, that I can think of from the top of my head:
Option 1: Fill a new array with the key values from the set of data, where the weight determines how often an item is repeated. The proportion in this array then matches the weighted distribution. Simply grab using
$arr[array_rand($arr)]
. While simple and easy to understand, this will explode in your face if there are a LOT of items, or if the weight values are really high.Option 2. Sum the weights. Pick a random number between 0 and sum-of-weights. Loop over the elements in the dataset, compare against the random number you picked. As soon as you hit one that is equal to or bigger then the random index, select that element.
Following our conversation in the comments below, here is a Pastebin with the code in it:
http://pastebin.com/bLbhThhj