Page 1 of 1

Array ordering with a twist

Posted: Sat Oct 29, 2005 10:33 am
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

Posted: Sat Oct 29, 2005 12:39 pm
by feyd
Create a comparison function and use usort()

Posted: Sat Oct 29, 2005 2:38 pm
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.