Array ordering with a twist

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
langfeld
Forum Newbie
Posts: 2
Joined: Sat Oct 29, 2005 10:23 am

Array ordering with a twist

Post by langfeld »

I have the following array:

Code: Select all

Array
(
    [0] => Team Object
        (
            [id] => 0
            [name] => Redgate
            [played] => 4
            [won] => 2
            [drawn] => 1
            [lost] => 1
            [points] => 7
            [goals_for] => 12
            [goals_against] => 8
            [goal_difference] => 4
        )

    [1] => Team Object
        (
            [id] => 1
            [name] => Formby
            [played] => 4
            [won] => 1
            [drawn] => 1
            [lost] => 2
            [points] => 4
            [goals_for] => 10
            [goals_against] => 11
            [goal_difference] => -1
        )

    [2] => Team Object
        (
            [id] => 2
            [name] => Southport
            [played] => 4
            [won] => 1
            [drawn] => 2
            [lost] => 1
            [points] => 5
            [goals_for] => 12
            [goals_against] => 15
            [goal_difference] => -3
        )

)
I need to order each of the elements of the array in the following way:
points (big->small)
if the number of points is the same between two elements then:
goal_difference (big->small)
if the goal difference is the same:
goals_for (big->small)
if the number of goals for is the same:
name (Alphabetically).

Does anyone know how best to go about doing this?

Ta,
Ben
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Create a comparison function and use usort()
langfeld
Forum Newbie
Posts: 2
Joined: Sat Oct 29, 2005 10:23 am

Post by langfeld »

Unfortunately usort() is just too simple for this application. I need to order the records in a football (soccer) league table firstly by points (which could be done by usort), but then some records may have the same value for the points field, in which case they must be sorted by the goal_difference field. If this is the same, they must then be sorted by the number of games won, and if this is the same, they must be sorted by the name field alphabetically. On other advice, I believe a bubble sort to be the most effective method of attacking this problem, and am trying to work through such.
Post Reply