php 条件语句

esyap4oy  于 2023-02-18  发布在  PHP
关注(0)|答案(1)|浏览(135)

我正试图根据学生的分数生成一份报告书。在表格中,我有一个复选框,如果学生缺席,教师可以从中打勾,如果是这种情况,则标记的值必须更改为AB,注解为缺席,而它可以将值更改为“AB”,这段代码不能提供学生“缺席”的注解,而是将“未通过”作为注解。2我应该在代码中修改什么?

if (isset($_POST['absent']) && (empty($mark)))
    {
        $mark="AB";
        $comment="Absent";
    }
    if($mark < 101 && $mark >=0)
    {   $comment="";
        if($grade > 9){
            $score="";
            if($mark >=75 and $mark <= 100 ){
                $score=1;
            $comment="Distinction";
            }else if($mark >= 70 and $mark <=74){
                $score=2;
            $comment="Distinction";
            }else if($mark >= 65 and $mark <= 69 ){
                $score=3;
            $comment="Merit";
            }else if($mark >= 60 and $mark <=64){
                $score=4;
            $comment="Merit";
            }else if($mark >= 55 and $mark <= 59){
                $score=5;
            $comment="Credit";
            }else if($mark >= 50 and $mark <= 54){
                $score=6;
            $comment="Credit";
            }else if($mark >= 45 and $mark <= 49){
                $score=7;
            $comment="Pass";
            }else if($mark >= 40 and $mark <= 44){
                $score=8;
            $comment="Pass";
            }else if($mark >= 0 and $mark <=39){
                $score=9;
            $comment="Fail";
            }else if($mark=="AB"){
                $comment="Absent";
            }
ivqmmu1c

ivqmmu1c1#

这种重复使用ElseIf的方式效率很低。这里建议使用switch。在PHP 8+中,你也可以使用match。Switch更有效,因为它只检查一次测试变量($mark)的值,而不是重复检查。

$comment=""; //default. 
if (isset($_POST['absent']) && (empty($mark)))
    {
        $mark="AB";
        $comment="Absent"; //default.
    }
switch((int)$mark < 101 && $grade > 9) {
    case in_array($mark, range(75,100)):
         $score=1;
         $comment="Distinction";
         break;
    case in_array($mark, range(70,74)):
         $score=2;
         $comment="Distinction";
         break;
    case in_array($mark, range(65,69)):
         $score=3;
         $comment="Merit";
         break;
    case in_array($mark, range(60,64)):
         $score=4;
         $comment="Merit";
         break;
    case in_array($mark, range(55,59)):
         $score=5;
         $comment="Credit";
         break;
    case in_array($mark, range(50,54)):
         $score=6;
         $comment="Credit";
         break;
    case in_array($mark, range(45,49)):
         $score=7;
         $comment="Pass";
         break;
    case in_array($mark, range(40,44)):
         $score=8;
         $comment="Pass";
         break;
    case in_array($mark, range(0,39)):
         $score=9;
         $comment="Fail";
         break;
}

相关问题