Main Content

Selecting RECENT and POPULAR news and trends for your web site users

Archive - Originally posted on "The Horse's Mouth" - 2015-01-19 08:31:27 - Graham Ellis

How do we give people recent news, or talk about recent trends or popular posts>?

The obvious answer is to take data for the last "n" days or months and analyse that. But whilst that's the obvious answer, it's also obviously a fairly crude measure as it gives undue influence as it changes to what happened at the distant (early) end of the period being analysed. For example, we hear about the "annual rate of inflation" and sometimes it's said to go down ... not because of something recent, but because a big rise in the price of [petrol/electricity/vegetables] has fallen off the equation from a year ago.

A far better solution is to run some sort of weighted measure where very recent events are given a significantly higher weight than old ones - and here's an example of how I've done this in a recent requirement to report on the currently most liked messages on our First Great Western Passenger Forum.

Coding in PHP:

  $scoreboard = array();
  $countdown = 50;
  $showrows = $countdown / 2;
  $r = mysql_query("select * from lykes order by timing desc limit $countdown");
  while (list($id,$post,$user,$when) = mysql_fetch_row($r)) {
    $scoreboard[$post] += ($countdown *= 0.92);
    # $scoreboard[$post] += $countdown--; /* Alternative to previous line */
  }


I have chosen to use three constants which work for this particular site at present:
• Consider most recent 50 likes
• Scale down the significance between each like to 92% of the previous one
• Display a maximum of half the number of articles which are in the window we've looked at
and while I could easily suggest more tuning (such as trimming article likes by date, differing factors and so forth) I've chosen to publish here with constants to make the algorithm easier to follow.


Click on image for most recent report!)


See the full code [here] (it turns out that the presentation code is far longer than the decaying average algorithm and try it out [here]. Find out about our PHP courses [here].