• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 221
  • Last Modified:

sorting a mutli-dimensional array in PHP

Hi there,

Well, the saga which is my first web application continues.  I recently had some help with an algorithm which calculates wins using a monthly tennis house-league matrix of scores and it works great.  But, with my limited exposure to web programming I've again reached a bit of a snag.

I have a 'Top Guns' sidebar.  I would like it to display the top 3 players in every house.  The information includes Name, Total Points, and now, Wins.  Here's what I'm looking to do...I would like the players to be sorted by Wins, and then by Total Points.  For example, if two players have 2 wins each..the one with the most points total points would appear ahead of the other guy.  Here's how my multi-dimensional array looks :

Array
(
    [0] => Array
        (
            [name] => Player 1
            [wins] => 3
            [score] => 24
        )

    [1] => Array
        (
            [name] => Player 2
            [wins] => 0
            [score] => 13
        )

    [2] => Array
        (
            [name] => Player 3
            [wins] => 1
            [score] => 12
        )

    [3] => Array
        (
            [name] => Player 4
            [wins] => 2
            [score] => 18
        )

)

Open in new window


I have the code to populate the array all set, I just need to be able to sort it according to my specifications.  Any help would be greatly appreciated!
0
duder78
Asked:
duder78
1 Solution
 
ncooCommented:
Just pass your array in to: usort($array, "winScore");

Details: http://uk3.php.net/usort

See code below.
<?php

$array = array(0 => array
        (
            'name' => 'Player 1',
            'wins' => '3',
            'score' => '24'
        ),

    1 => array
        (
            'name' => 'Player 2',
            'wins' => '0',
            'score' => '13'
        ),

    2 => array
        (
            'name' => 'Player 3',
            'wins' => '1',
            'score' => '12'
        ),

    3 => array
        (
            'name' => 'Player 4',
            'wins' => '2',
            'score' => '18'
        )

);

function winScore($a, $b)
{
    if ($a['wins'] == $b['wins']) {
		if ($a['score'] == $b['score']) {

			return 0;
		}
		return ($a['score'] < $b['score']) ? 1 : -1;
    }
    return ($a['wins'] < $b['wins']) ? 1 : -1;
}


usort($array, "winScore");

echo '<pre>';
print_r($array);

Open in new window

0
 
duder78Author Commented:
Works like a champ, thanks alot!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now