user827570
user827570

Reputation: 491

PHP Array ordering based on a rating formula?

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.

Upvotes: 1

Views: 122

Answers (3)

Dan LaManna
Dan LaManna

Reputation: 3501

Something along these lines of using usort should work:

usort($objects, function($a, $b) {
$rating_of_a = $a['rating'] / ($current_time - $a['date']);
$rating_of_b = $b['rating'] / ($current_time - $b['date']);

return ($rating_of_a < $rating_of_b) ? -1 : 1;
});

Upvotes: 0

Andrzej Ośmiałowski
Andrzej Ośmiałowski

Reputation: 1504

You have to use usort() function.

Upvotes: 1

cwallenpoole
cwallenpoole

Reputation: 82028

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');

Upvotes: 3

Related Questions