doulou1989
2011-12-12 21:00
浏览 37
已采纳

在CodeIgniter中使用PHP对多维数组进行排序以进行排名?

I'm looking to use the results in an array and sort them using a ranking algorithm similar to say Hacker News or Reddit.

For example, paraphrasing the HN algorithm: Score = P / (T+2)^G

where,
P = points of an item (e.g. votes + comments + likes)
T = time since submission (in hours)
G = Gravity, (on HN defaults to 1.8)

From what I understand, I need to use a PHP sorting array, but the PHP manual is confusing, and the similar answers on StackOverflow have very specific answers without many comments as to what the function is doing. e.g. here, here & here.

My data looks as follows

Array
(
    [0] => Array
        (
            [post_created] => 2011-12-12 07:18:17
            [post_num_likes] => 1
            [post_num_comments] => 0
            [post_message] => Some message
            [votes] => 16
        )

    [1] => Array
        (
            [post_created] => 2011-12-11 22:17:16
            [post_num_likes] => 0
            [post_num_comments] => 4
            [post_message] => Another message
            [votes] => 21
        )

    [2] => Array
        (
            [post_created] => 2011-12-11 20:21:11
            [post_num_likes] => 1
            [post_num_comments] => 2
            [post_message] => Next message
            [votes] => 1
        )

    [3] => Array
        (
            [post_created] => 2011-12-11 20:11:47
            [post_num_likes] => 0
            [post_num_comments] => 0
            [post_message] => Something else
            [votes] => 0
        )

    [4] => Array
        (
            [post_created] => 2011-12-11 20:09:46
            [post_num_likes] => 1
            [post_num_comments] => 0
            [post_message] => Another message 
            [votes] => 5
        )

So far as I understand, I need to do something like the following:

// Send array as 2nd parameter due to way you call functions in CodeIgniter
uksort($array, array('Class_name','postrank'));

function postrank($a, $b) {
    // some sorting function here
    return strcmp($a, $b);
}

I've tried copying and pasting various functions, but as they're not so well commented, it's hard to know what's going on.

How might I go about recreating a similar post ranking sorting function with the above data?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dougang6178 2011-12-12 21:29
    已采纳

    amidoinitrite?

    SELECT * , (
    votes + post_num_comments + post_num_likes - 1
    ) / POW( ROUND( (
    TIME_TO_SEC( TIMEDIFF( NOW( ) , post_created ) ) / 3600 ) + 2 ) , 1.8
    ) AS score
    FROM hacker_news
    ORDER BY score DESC
    

    enter image description here

    The formula on website is actually: Score = (P-1) / (T+2) ^ G

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(2条)

相关推荐 更多相似问题