PHP升级成绩

时间:2012-04-29 11:44:44

标签: php

我有两个阵列; $marks$grades$marks包含由学生评分的分数,$grades是通过使用以下函数循环$marks获得的。

 function convertMarkToGrade($mark)
    {
        if($mark<21)
            return "D";
        else if($mark<33)
            return "C";
        else if($mark<41)
            return "B";
        else if($mark<=50)
            return "A";
    }

问题是我想使用以下标准升级$grades数组中的最小和最小等级

  1. 从最低等级到高等等等进行升级,即B到A,C到B等

  2. 如果等级达到等级,则升级最高等级。

  3. 例如:
    $marksarray(25,43,36,16,28)。我们得到$gradesarray("C","A","B","D","C")。我希望生成一个$upgraded_grades =array("C","A","B","C","B"),即D等级(最低等级)升级,C等级(第二小等级,但最高等级)也升级。

    我怎么能在php中做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以使用关联数组。这是一种方法:

<强>被修改:     

//create associative array that has values as array of marks
$grades_arr = array("D" => array(), "C" => array(), "B" => array(), "A" => array() );

for($i = 0;$i < count($grades);$i++)
    array_push($grades_arr[$grades[$i]], $marks[$i]);

$loop = 0;
foreach($grades_arr as $key => &$value){
    if(empty($value))
        continue;

    if($loop == 2)
        break; //break after two upgrades
    else{
        $max = max($value);
        //unset the variable
        $value = array_diff($value, array($max));
        $value = array_values($value); 
        //push it into next higher grade
        array_push($grades_arr[chr(ord($key)-1)], $max);
        $loop++;
    }
}

print_r($grades_arr);

答案 1 :(得分:0)

如果我理解你,你需要这个:

    $letterMark = ....; // "A","B","C" or "D"

    /* decrese number, that is increse letter by one
       but make sure it does not exceed 'A' mark 
    */
    $ordedMark = max(ord($letterMark)- 1, ord('A')); 
    $upscaledMark = chr($ordedMark);

    return $upscaledMark;

我将此代码段打包到函数中:http://codepad.viper-7.com/i9Rtgi