Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to sort the contens of an array and then enter it into a HTML table. The array needs to be sorted based on the number of goals, and if two teams have the one with the most players needs to be placed higher. This is a sample of the array:

Array
(
    [0] => Array
        (
            [id] => 1
            [team] => Manchester United
            [goals] => 210
            [country] => england
            [players] => 10
        )

    [1] => Array
        (
            [id] => 2
            [team] => Manchester City
            [goals] => 108
            [country] => england
            [players] => 12
        )

    [2] => Array
        (
            [id] => 3
            [team] => Liverpool
            [goals] => 108
            [country] => england
            [players] => 15
        )
)

I've never done sorting in PHP and I only have some experience with arrays, they weren't nested like this.

share|improve this question

1 Answer 1

All you need is usort

usort($data, function ($a, $b) {
    if ($a['goals'] == $b['goals'])
        return $a['players'] > $b['players'] ? - 1 : 1;
    return $a['goals'] > $b['goals'] ? -1 : 1;
});

print_r($data);

Output

Array
(
    [0] => Array
        (
            [id] => 1
            [team] => Manchester United
            [goals] => 210                    <--- Highest goal top
            [country] => england
            [players] => 10
        )

    [1] => Array
        (
            [id] => 3
            [team] => Liverpool
            [goals] => 108                    <--- Same Score found
            [country] => england
            [players] => 15                           Use This ---|
        )

    [2] => Array
        (
            [id] => 2
            [team] => Manchester City
            [goals] => 108                    <--- Same Score found
            [country] => england
            [players] => 12                           Use This ---|
        )

)

See Live Demo

share|improve this answer
    
Is this part correct? (($a < $b) ? 1 : 1) my tests lead me to believe it should be (($a < $b) ? 1 : -1), other than that tho +1. –  pebbl Apr 12 '13 at 17:05
    
@pebbl thanks for the observation .... it was an expensive typo –  Baba Apr 12 '13 at 17:15
    
no worries, nice one on the eloquent solution, my approach was rather more clunky. –  pebbl Apr 12 '13 at 17:28
    
Your observation made me realize i need to make the code more readable .. thanks –  Baba Apr 12 '13 at 17:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.