在PHP中按多个值排序数组并插入HTML表
我试图对数组的内容进行排序,然后将其输入HTML表。阵列需要根据进球数进行排序,如果两支球队拥有最多球员的那支球队,则需要将其放在更高的位置。这是阵列的一个示例:在PHP中按多个值排序数组并插入HTML表,php,arrays,sorting,Php,Arrays,Sorting,我试图对数组的内容进行排序,然后将其输入HTML表。阵列需要根据进球数进行排序,如果两支球队拥有最多球员的那支球队,则需要将其放在更高的位置。这是阵列的一个示例: Array ( [0] => Array ( [id] => 1 [team] => Manchester United [goals] => 210 [country] => engl
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做过排序,我只对数组有一些经验,它们不是这样嵌套的。您只需要
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);
数组
(
[0]=>阵列
(
[id]=>1
[球队]=>曼联
[进球]=>210个英格兰
[玩家]=>10
)
[1] =>阵列
(
[id]=>3
[团队]=>利物浦
[进球]=>108个英格兰
[玩家]=>15使用此---|
)
[2] =>阵列
(
[id]=>2
[团队]=>曼城
[进球]=>108个英格兰
[玩家]=>12使用此---|
)
)
这部分正确吗
($a<$b)?1:1
我的测试让我相信它应该是($a<$b)?1:1)
,除此之外tho+1。不用担心,很好的解决方案,我的方法相当笨拙。你的观察让我意识到我需要让代码更具可读性。。谢谢
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 ---|
)
)