You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用uasort()对CSV中的学生条目按GPA降序排序?

没问题,我来帮你搞定这个按GPA降序排序的需求!咱们一步步来调整你的代码,用uasort()实现你想要的效果。

首先,你现有代码的问题是直接读取CSV行后就输出了,没有先排序。我们需要先把所有学生数据整理成数组,再用uasort()结合自定义比较规则来排序,最后再输出表格。

关键步骤说明:

  • 更健壮的CSV解析:推荐用str_getcsv()代替直接explode(','),它能更好地处理CSV格式的细节(比如字段含空格或特殊字符的情况,虽然你的CSV现在没有,但更稳妥)。
  • 自定义比较函数:uasort()需要一个回调函数来定义排序规则,我们要基于GPA字段(数组索引第6位,从0开始计数)做降序比较,记得把GPA转成浮点型,避免字符串比较的坑。
  • 排序后输出:排序完成后再循环输出表格行,就能得到你想要的顺序了。

修改后的完整代码:

// 输出表格表头
echo "<table border='1'>";
echo "<tr>";
echo "<th> Student ID </th>";
echo "<th> First Name </th>";
echo "<th> Last Name </th>";
echo "<th> Birthdate </th>";
echo "<th> Completed Courses </th>";
echo "<th> Failed Courses </th>";
echo "<th> GPA </th>";
echo "<th> Status </th>";
echo "</tr>";

// 读取并解析CSV文件
$csvFile = "../databases/students.csv";
$students = [];
$lines = file($csvFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach ($lines as $line) {
    // 用str_getcsv解析每行,得到学生数据数组
    $studentData = str_getcsv(trim($line));
    // 跳过空行或格式不正确的行
    if (count($studentData) >= 8) {
        $students[] = $studentData;
    }
}

// 用uasort按GPA降序排序
uasort($students, function($a, $b) {
    // 把GPA转成浮点型,确保数值比较
    $gpaA = (float)$a[6];
    $gpaB = (float)$b[6];
    
    // 降序规则:a的GPA比b大,返回-1让a排在前面
    if ($gpaA > $gpaB) {
        return -1;
    } elseif ($gpaA < $gpaB) {
        return 1;
    } else {
        return 0;
    }
});

// 输出排序后的学生数据
foreach ($students as $student) {
    list($studentID, $fName, $lName, $dob, $completedCourses, $failedCourses, $gpa, $status) = $student;
    print <<< HERE
    <tr>
        <td> $studentID </td>
        <td> $fName </td>
        <td> $lName </td>
        <td> $dob </td>
        <td> $completedCourses </td>
        <td> $failedCourses </td>
        <td> $gpa </td>
        <td> $status </td>
    </tr>
HERE;
}

echo "</table>";

代码细节解释:

  • FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES:读取CSV时自动跳过空行和换行符,避免处理无效数据。
  • 比较函数里的(float)转换:确保GPA是按数值大小比较,而不是字符串(比如"5"和"4.0"字符串比较会有问题,转成浮点型就正确了)。
  • uasort()会保留数组的键,但这里我们不需要键,只是用它的自定义排序能力,也可以用usort(),效果一样。

运行这段代码后,输出的表格就会按照GPA从高到低排列,完全符合你给出的期望结果。

内容的提问来源于stack exchange,提问作者Robin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:05:50