0

我正在尝试对数组的内容进行排序,然后将其输入到 HTML 表中。该数组需要根据进球数进行排序,如果两支球队拥有最多球员的球队,则需要将其放置在更高的位置。这是数组的示例:

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
        )
)

我从来没有在 PHP 中进行过排序,而且我对数组只有一些经验,它们不是这样嵌套的。

4

1 回答 1

2

所有你需要的是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);

输出

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 ---|
        )

)

观看现场演示

于 2013-04-12T16:56:36.277 回答