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

时间:2011-12-12 21:00:11

标签: php codeigniter ranking sorting

我希望在数组中使用结果,并使用类似于Hacker News或Reddit的排名算法对它们进行排序。

For example, paraphrasing the HN algorithm:     得分= 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)

根据我的理解,我需要使用PHP排序数组,但PHP手册令人困惑,而StackOverflow上的类似答案有非常具体的答案,没有很多关于函数正在做什么的评论。例如herehere& here

我的数据如下

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
        )

据我了解,我需要做以下事情:

// 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);
}

我尝试过复制和粘贴各种功能,但由于评论不是很好,所以很难知道发生了什么。

如何使用上述数据重新创建类似的排名后排序功能?

3 个答案:

答案 0 :(得分:2)

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

网站上的公式实际上是:得分=(P-1)/(T + 2)^ G

答案 1 :(得分:2)

我早于5.3的PHP示例代码:)

<?php
function customSort($a, $b){
    foreach(array('a', 'b') as $vn){
        $tmp = $$vn;
        $p = $tmp['post_num_likes'] + $tmp['post_num_comments'] + $tmp['votes'];
        $t = ceil((time() - strtotime($tmp['post_created'])) / 3600);
        $$vn = $p / pow($t + 2, 1.81);
    }
    return $a - $b;
}
usort($array, 'customSort');

var_dump($array);

答案 2 :(得分:1)

$score = function($arr) {
    extract($arr);
    return ($votes + $comments + $likes) / pow($created_time + 2, 1.8);
};

usort($array, function($a, $b) use ($score) {
    return $score($a) - $score($b);
});

这需要php 5.3因为我使用了匿名函数。