使用关联数组计算平均成绩

时间:2018-03-11 10:34:49

标签: php

如果我的平均得分为:

$average = 95.00000000

我有一个阵列:

$grades = array("91-100"=>"A+","80-89"=>"A","70-79"=>"B","60-69"=>"C","50-59"=>"D","0-49"=>"F");

当我尝试通过以下方式获得平均成绩时:

$grade = $grades[$average];

我收到错误:

  

注意:未定义索引:95.00000000

我认为问题来自阵列的关键问题,但有没有办法实现我想要实现的目标?

2 个答案:

答案 0 :(得分:4)

您必须遍历密钥,并检查您的值是否在它们之间:

$grades = array("91-100"=>"A+","80-89"=>"A","70-79"=>"B","60-69"=>"C","50-59"=>"D","0-49"=>"F");
$average = 95.00000000 ;

$grade = '' ;
foreach ($grades as $val => $cur_grade) {
    list($min, $max) = explode('-', $val); // split key into min and max
    if ($average >= $min && $average <= $max) { // compare
        $grade = $cur_grade ; // get the value
        break ; // stop the loop
    }
}
echo $grade ;

输出:

A+

请注意,如果您的$average不在范围内(例如69.9),那么它将不匹配。所以你可以使用“90-100”,“80-90”,......

$grades = array("90-100"=>"A+","80-90"=>"A","70-80"=>"B","60-70"=>"C","50-60"=>"D","0-50"=>"F");
$average = 69.9 ;
// ..code above..
echo $grade ; // Outputs "C"

并且

$average = 70.0 ;
// ..code above..
echo $grade ; // Outputs "B"

答案 1 :(得分:0)

我建议将等级数组更改为更简单的结构,这样您就可以获得更简单,更可预测的代码

<?php
$average = 95.00000000;
$grades = array(
    array(
        'grade' => 'A+',
        'max' => 100,
        'min' => 90
    ),
    array(
        'grade' => 'A',
        'max' => 89,
        'min' => 80
    ),
    array(
        'grade' => 'B',
        'max' => 79,
        'min' => 70
    ),
    array(
        'grade' => 'C',
        'max' => 69,
        'min' => 60
    ),
    array(
        'grade' => 'D',
        'max' => 59,
        'min' => 50
    ),
    array(
        'grade' => 'F',
        'max' => 49,
        'min' => 0
    ),
);

$result = null;
$averageScore = (int) floor($average); // it's better to compare int to int instead of float to int
foreach($grades as $grade) {
    if ($average < $grade['max'] && $average >= $grade['min']) {
        $result = $grade['grade'];
        break;
    }
}
if ($result !== null) {
    echo 'Your grade is: ' . $result;
} else {
    echo 'Grading error, please ask your professor for details!';
}