John Garretson
John Garretson

Reputation: 15

Sort a 2d array by a column then print and remove rows

I have the following array setup called $players:

Array(
    [4153234567] => Array(
        [name] => JohnnyAppleSeed
        [rating] => 00
    )
    [4807173711] => Array(
        [name] => admin
        [rating] => 6000
    )
    [4801234562] => Array(
        [name] => 4801234562
        [rating] = > 00
    )
)

I need to sort this array and echo:

$name of person with highest rating
$name of person with lowest rating

then remove these people from the array im looking at and repeat till I have moved through everyone.

Any ideas?

Upvotes: 0

Views: 83

Answers (2)

gview
gview

Reputation: 15361

Given the data you provided, you're actually going to need to use uasort -- that is unless the keys of the array (ie.4153234567) don't matter to you. Otherwise the principle and sorting routine is the same.

Also to remove items you would use unset(). If you save the keys in to $first, $last, then

unset($players[$first]);
unset($players[$last]);

Upvotes: 0

Jimtronic
Jimtronic

Reputation: 1209

Try usort

 usort($players, "player_sort");

 function player_sort($a,$b) {
      return $a['rating']>$b['rating'];
 }

http://www.php.net/manual/en/function.usort.php

Once sorted, you can take the first and last element to get the highest and lowest.

Upvotes: 4

Related Questions