按数字降序排列数组
Sort array with numbers descending
我从我做的测验中得到了结果,结果是数字(总计:44/33/22/11,例如 A = 11,B = 44,C = 33,D = 22)我希望屏幕上打印的结果按降序排列,首先是最高 (44),然后是第二、第三,然后是最低 (11)。
成功了(post 另一个 post 一个小时前有人帮助了我)
问题是我还有 2 个参数。
例如:
A - 40 - 90
B - 29 - 91
C - 55 - 92
D - 90 - 93
现在我希望它在屏幕上显示为 D/C/A/B 按第二个参数($percent(90/55/29/40)
降序
代码:
$percentA = $totalA * 4;
$percentB = $totalB * 4;
$percentC = $totalC * 4;
$percentD = $totalD * 4;
$letters = ['A', 'B', 'C', 'D'];
$temp_array = [];
$results = array(
'A' => ['percent' => $percentA, 'value'=>'90'],
'B' => ['percent' => $percentB, 'value'=>'91'],
'C' => ['percent' => $percentC, 'value'=>'92'],
'D' => ['percent' => $percentD, 'value'=>'93']
);
//rsort($results);
for($i = 0; $i < count($results); $i++) {
$name = $letters[$i];
$percent = $results[$letters[$i]]['percent'];
$value = $results[$letters[$i]]['value'];
$new_array = ['name' => $name, 'percent' => $percent ,'value'=>$value];
array_push($temp_array, $new_array);
}
It sorts but it sorts on the key of the array (3/2/1/0) I want to to sort on percent (10/20/30/40 for example)
krsort($temp_array);
foreach ($temp_array as $key => $val) {
}
使用排序:
usort($yourArray, function($a, $b) {
if ($a['value'] == $b['value']) {
return 0;
}
return ($a['value'] < $b['value']) ? -1 : 1;
});
我从我做的测验中得到了结果,结果是数字(总计:44/33/22/11,例如 A = 11,B = 44,C = 33,D = 22)我希望屏幕上打印的结果按降序排列,首先是最高 (44),然后是第二、第三,然后是最低 (11)。 成功了(post 另一个 post 一个小时前有人帮助了我) 问题是我还有 2 个参数。
例如:
A - 40 - 90 B - 29 - 91 C - 55 - 92 D - 90 - 93
现在我希望它在屏幕上显示为 D/C/A/B 按第二个参数($percent(90/55/29/40)
降序代码:
$percentA = $totalA * 4;
$percentB = $totalB * 4;
$percentC = $totalC * 4;
$percentD = $totalD * 4;
$letters = ['A', 'B', 'C', 'D'];
$temp_array = [];
$results = array(
'A' => ['percent' => $percentA, 'value'=>'90'],
'B' => ['percent' => $percentB, 'value'=>'91'],
'C' => ['percent' => $percentC, 'value'=>'92'],
'D' => ['percent' => $percentD, 'value'=>'93']
);
//rsort($results);
for($i = 0; $i < count($results); $i++) {
$name = $letters[$i];
$percent = $results[$letters[$i]]['percent'];
$value = $results[$letters[$i]]['value'];
$new_array = ['name' => $name, 'percent' => $percent ,'value'=>$value];
array_push($temp_array, $new_array);
}
It sorts but it sorts on the key of the array (3/2/1/0) I want to to sort on percent (10/20/30/40 for example)
krsort($temp_array);
foreach ($temp_array as $key => $val) {
}
使用排序:
usort($yourArray, function($a, $b) {
if ($a['value'] == $b['value']) {
return 0;
}
return ($a['value'] < $b['value']) ? -1 : 1;
});