0

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
no worries, nice one on the eloquent solution, my approach was rather more clunky.
Your observation made me realize i need to make the code more readable .. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.