在PHP中按多个值对数组进行排序并插入到HTML表中

时间:2013-04-12 16:51:54

标签: php arrays sorting

我正在尝试对数组的匹配进行排序,然后将其输入到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中进行排序,我只对数组有一些经验,它们没有像这样嵌套。

1 个答案:

答案 0 :(得分: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);

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