Rank array managing duplicate ranks

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
inneedofhelp
Forum Newbie
Posts: 1
Joined: Wed Mar 09, 2011 1:49 pm

Rank array managing duplicate ranks

Post by inneedofhelp »

i am using....

$myarray = array(3,5,2,3,1);

$sorted_array = $myarray;
$grouped_array = array();
sort($sorted_array);
foreach ($sorted_array as $rank => $entry) {
// Initialize the entry if it doesn't already exist
if (empty($grouped_array[$entry])) {
$grouped_array[$entry]['count'] = 1.0;
$grouped_array[$entry]['total'] = $rank + 1; // Account for 0-based array
} else {
$grouped_array[$entry]['count'] += 1.0;
$grouped_array[$entry]['total'] += $rank + 1; // Account for 0-based array
}
}
$myarray2 = array();
foreach ($myarray as $entry) {
// Get the average
$myarray2[] = $grouped_array[$entry]['total'] / $grouped_array[$entry]['count'];
}

print_r($myarray2);


to sort the array.

for this array 3 is in the array twice and this is handled by giving these two values the rank 3.5 but this only works if there are only 2 duplicates.

I need this to work for any number of duplicates so when a value is the same it assigns the rank to the mean of the ranks involved in the tie

e.g.....
$myarray = array(3,3,2,3,1);
i need the ranks to be: 4, 4, 2, 4, 1

$myarray = array(3,1,3,2,3,1);
i need the ranks to be: 5, 1.5, 5, 3, 5, 1.5
Post Reply