0
我必須做一個排名功能。配合多維數組排序功能
在我的$通道數組中,我有'user','username','note'和'classement'鍵。
我想設置'classement'鍵,按'note'鍵排序,按'username'鍵排序。
這裏是我的嘗試:
for ($i = 0; $i < sizeof($passages); $i++) {
for ($j = 0; $j < sizeof($passages); $j++) {
$test = $this->compare($passages[$i]['note'], $passages[$j]['note']);
if ($test < 0) {
$tmp = $passages[$j];
$passages[$j] = $passages[$i];
$passages[$i] = $tmp;
} else if ($test >= 0) {
$tmp = $passages[$i];
$passages[$i] = $passages[$j];
$passages[$j] = $tmp;
}
}
}
比較功能:
if ($a==$b) return 0;
return ($a<$b)?-1:1;
在這個排名功能,我增加了一個功能,採取關係的護理:
$rank = 1;
for ($i = 0; $i < $nbTotal; $i++) {
// Si la note du passage actuel est égale à la note du passage précédent,
// le classement est égal au classement du passage précédent
if ($i > 0 && $passages[$i]['note'] == $passages[$i - 1]['note']) {
$passages[$i]['classement'] = $passages[$i - 1]['classement'];
}
// Sinon le classement est égal à la valeur de $rank
else {
$passages[$i]['classement'] = $rank;
}
$rank++;
}
我測試我的函數,它返回一個由用戶ID和'classement'鍵=用戶ID順序排序的數組。
我得到什麼:
$passages = array(
array(['id'] => "1"
['username'] => "1124",
['note'] => "22",
['classement'] => "1"),
array(['id'] => "2",
['username'] => "1001",
['note'] => "10",
['classement'] => "2"),
array(['id'] => "3",
['username'] => "1100",
['note'] => "15",
['classement'] => "3"),
array(['id'] => "4",
['username'] => "1120",
['note'] => "5",
['classement'] => "4"),
array(['id'] => "5",
['username'] => "1200",
['note'] => "15",
['classement'] => "5")
);
我想要什麼:
$passages = array(
array(['id'] => "2"
['username'] => "1001",
['note'] => "10",
['classement'] => "4"),
array(['id'] => "3",
['username'] => "1100",
['note'] => "15",
['classement'] => "2"),
array(['id'] => "4",
['username'] => "1120",
['note'] => "5",
['classement'] => "5")
array(['id'] => "1",
['username'] => "1124",
['note'] => "22",
['classement'] => "1"),
array(['id'] => "5",
['username'] => "1200",
['note'] => "15",
['classement'] => "2")
);
非常感謝!這正是我想要的!而我的代碼現在更小,這個解決方案。 –