joeshmoe
joeshmoe

Reputation: 119

Sort array by key value and then get 5 highest and lowest values in array

I have an array called "playersArray" that looks like this:

Array (
    [0] => Array ( [name] => Joe [holders] => 0 )
    [1] => Array ( [name] => Bob [holders] => 100 )
    [2] => Array ( [name] => Jake [holders] => 100 )
    [3] => Array ( [name] => Mike [holders] => 100 )
    [4] => Array ( [name] => Tim [holders] => -0.0145 )
    [5] => Array ( [name] => Frank[holders] => 100 ) 
    [6] => Array ( [name] => Scott [holders] => 0.0583 ) 
    [7] => Array ( [name] => Doug[holders] => 0.1308 ) 
    [8] => Array ( [name] => Tommy [holders] => 0.2516 ) 
    [9] => Array ( [name] => Eric [holders] => 100 ) 
)

I have a function to sort this array by the "holders" value:

function compareHolders($a, $b) {

    $aPoints < $a['holders'];
    $bPoints < $b['holders'];

    return strcmp($aPoints, $bPoints);

}

I loop through another array to create this array:

foreach ($players as $player) {
    $player['name'] = $athlete['name'];
    $player['holders'] = $total_result_yesterday;
    $playersArray[] = $player;
}

I am trying to sort the array by "holder" value:

usort($playersArray, 'compareHolders');

print_r($playersArray);

Finally, I am trying to get the 5 highest and 5 lowest "holder" values in the newly sorted array:

$first_5_players = array_slice($playersArray, 0, 5, true);
$last_5_players = array_slice($playersArray, -5);

However, the sorting is not working correctly. The values due not show in sequential order as desired. How can I get the sorting to work correctly? Thank you!

Upvotes: 0

Views: 397

Answers (2)

Niellles
Niellles

Reputation: 878

You are not actually comparing the two values in compareHolders(), because you're not declaring $aPpoints and $bPoints.

This should work:

function compareHolders($a, $b) {

    $aPoints = $a['holders'];
    $bPoints = $b['holders'];

    return strcmp($aPoints, $bPoints);

}

or alternatively you could just return:

return strcmp($a['holders'], $b['holders']);

And then you could get rid of the strcmp(), since you're not comparing strings.

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

your sorting function compareHolders is not correct. $aPoints and $bPoints are not defined. Since values for holders key are numeric you can use the comparision operators. Try doing following:

function compareHolders($a, $b) {
    if ($a['holders'] == $b['holders']) {
        // return 0 if equal
        return 0;
    }
    return ($a['holders'] > $b['holders']) ? -1 : 1;
}

Upvotes: 3

Related Questions