douzhi3454 2012-01-26 03:42
浏览 34
已采纳

基于评级公式的PHP数组排序?

I'm trying to order an array of results using a rating forumula I have created, it works by creating a new rating value based on time since posting.

Heres the rating formula: Ratings decrease overtime (Times are in unix timestamps format)

$new_rating = $current_rating / ($current_time - $post_time);

Array
(
[0] => Submissions Object
    (
        [title] => Exploits Emerge For Linux Privilege Escalation Flaw
        [link] => http://test.com
        [description] => test description test
        [tags] => hardware,government,libya
        [rating] => 10
        [date] => 1327546314
    )

[1] => Submissions Object
    (
        [title] => High School Students Send Lego Man 24 Kilometers High
        [link] => http://test.com
        [description] => test description test
        [tags] => hardware,government,libya
        [rating] => 5
        [date] => 1327546305
    )

)

My question is how do I sort this array using the above formula? or is their a way I can insert this formula into the mysql query statement?

Thanks a lot everyone.

  • 写回答

3条回答 默认 最新

  • drwxg62286 2012-01-26 03:47
    关注

    You're going to want to use usort along with a custom sorting function.

    function get_rating($obj)
    {
        $obj->rating / (time() - $obj->date);
    }
    
    function my_compare_func($a, $b)
    {
        $a = get_rating($a);
        $b = get_rating($b);
        if($a == $b) return 0;
        return ($a > $b)? 1: -1;
    }
    
    usort($array_of_objs, 'my_compare_func');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?