user2275265
user2275265

Reputation: 1

Sorting an array by multiple values in PHP and inserting into HTML table

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.

Upvotes: 0

Views: 118

Answers (1)

Baba
Baba

Reputation: 95141

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

Upvotes: 2

Related Questions