我有一个数组,其中包含用户名和分数。
我首先按照最高分对它进行排序。效果很好,但是那些得分与我相同的人都希望按名称进行排序,其余分数为0的人也必须按名称进行排序。
我正在使用此功能按r_nb_today
(分数)进行排序:
function sortByNbToday($a, $b) {
$a = $a['r_nb_today'];
$b = $b['r_nb_today'];
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1;
}
usort($disp_user_arr, 'sortByNbToday');
这是数组输出:
Array
(
[0] => Array
(
[u_id] => 9
[u_name] => Souhaila S.
[r_nb_today] => 7
)
[1] => Array
(
[u_id] => 59
[u_name] => Cirine E.
[r_nb_today] => 2
)
[2] => Array
(
[u_id] => 64
[u_name] => Cyrine B.
[r_nb_today] => 1
)
[3] => Array
(
[u_id] => 8
[u_name] => Jihen B. R.
[r_nb_today] => 1
)
[4] => Array
(
[u_id] => 18
[u_name] => Otail J.
[r_nb_today] => 0
)
[5] => Array
(
[u_id] => 15
[u_name] => Rim H.
[r_nb_today] => 0
)
[6] => Array
(
[u_id] => 12
[u_name] => Bassem D.
[r_nb_today] => 0
)
[7] => Array
(
[u_id] => 75
[u_name] => Mariem N.
[r_nb_today] => 0
)
[8] => Array
(
[u_id] => 66
[u_name] => Khaoula K.
[r_nb_today] => 0
)
[9] => Array
(
[u_id] => 74
[u_name] => Ghada J.
[r_nb_today] => 0
)
[10] => Array
(
[u_id] => 62
[u_name] => Alaeddine M.
[r_nb_today] => 0
)
[11] => Array
(
[u_id] => 79
[u_name] => Khaled B.
[r_nb_today] => 0
)
[12] => Array
(
[u_id] => 71
[u_name] => Desiree Y.
[r_nb_today] => 0
)
答案 0 :(得分:2)
您可以使用多分类
$r_nb_today = array_column($arr, 'r_nb_today');
$u_name = array_column($arr, 'u_name');
array_multisort($r_nb_today, SORT_NUMERIC, SORT_DESC,
$u_name, SORT_NATURAL, SORT_ASC, $arr);
如果要更改名称,请对$u_name
使用sort_desc。
以下是有关array_multisort的详细信息。
答案 1 :(得分:2)
稍微更改一下代码:-
function sortByNbToday($a, $b) {
if ($a['r_nb_today'] == $b['r_nb_today']){
return strcmp($a["u_name"], $b["u_name"]); // add string comparison code
}
return ($a['r_nb_today'] > $b['r_nb_today']) ? -1 : 1;
}
usort($disp_user_arr, 'sortByNbToday');
答案 2 :(得分:1)
function sortByNbToday($a, $b) {
$score1 = $a['r_nb_today'];
$score2 = $b['r_nb_today'];
if ($score1 != $score2){
return -1 * ($score1 - $score2);
}
return strcmp($a['u_name'],$b['u_name']);
}
如果两个分数不同,则返回其结果,否则返回来自u_name
字符串比较的结果。