PHP如何将foreach循环输出结果按得分从高到低降序排列
问题原因
你原有代码出错主要是两个核心问题:
- 赋值逻辑错误:
$sortedarr = [] = $userpoints;这行语法逻辑错误,每次循环都会清空sortedarr数组,最终你传入sort()的是无效数据,所以输出空白。 - 排序逻辑错误:即使你把拼接好的「姓名: 得分
」字符串存入数组再排序,也会按字符串规则排序,而不是按得分数值从高到低排序,达不到需求。
另外你原来while(...);后接array_pop的写法也不规范,是因为把查询结束返回的false也存入了数组,才需要额外删除末尾元素,完全可以用更稳妥的循环写法避免这个操作。
解决方案1(推荐:SQL层面直接计算排序,性能更好)
直接在查询语句里计算所有题目的总分,然后按总分降序排序,不需要PHP额外处理排序逻辑,代码更简洁执行效率更高:
// SQL里直接计算q1到q40的总分,别名total_points,直接按总分倒序 $sql = mysqli_query($conn, "SELECT *, (q1points + q2points + q3points + q4points + q5points + q6points + q7points + q8points + q9points + q10points + q11points + q12points + q13points + q14points + q15points + q16points + q17points + q18points + q19points + q20points + q21points + q22points + q23points + q24points + q25points + q26points + q27points + q28points + q29points + q30points + q31points + q32points + q33points + q34points + q35points + q36points + q37points + q38points + q39points + q40points) as total_points FROM `live` ORDER BY total_points DESC"); $liveuserscores = []; while($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)){ $liveuserscores[] = $row; } // 遍历输出即可,已经是按得分从高到低排好的 foreach ($liveuserscores as $user) { echo $user['name'].": ".number_format($user['total_points'])."<br>"; }
解决方案2(PHP层面处理排序)
如果场景限制不能修改SQL查询逻辑,可以在PHP端计算总分后用自定义规则排序:
error_reporting(E_ALL); ini_set('display_errors', '1'); $sql = mysqli_query($conn,"SELECT * FROM `live`"); $liveuserscores = []; while($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)){ // 提前计算每个用户的总分存入数组 $total = 0; for($i=1;$i<=40;$i++){ $total += $row["q{$i}points"]; } $row['total_points'] = $total; $liveuserscores[] = $row; } // 自定义排序规则:按总分降序 usort($liveuserscores, function($a, $b){ return $b['total_points'] - $a['total_points']; }); // 输出排序后的结果 foreach ($liveuserscores as $user) { echo $user['name'].": ".number_format($user['total_points'])."<br>"; }
内容的提问来源于stack exchange,提问作者Glen Keybit
相关产品推荐
相关产品推荐

