PHP:按类别平均评分

时间:2013-04-28 19:12:32

标签: php arrays calculator

我对PHP很新,并尝试对类项目进行排序。我已经赶走了,看不清楚,这是剩下的最后一块。

我有一个表单 - 基本上提交2个数组我试图根据类别分组确定平均分数。 1.($ _post ['category']),($ _post ['score']) - 类别是基于文本的数组,分数显然是基于数字的。

我如何找到每个类别的平均分数?我已经尝试了各种选项来映射两个数组,然后尝试平均成绩。我可以很容易地获得平均总得分,但是找到各个方法分别对每个类别进行此操作会让我感到沮丧。

我需要对每个类别分数应用权重,但是一旦得到上述分类,这似乎很容易。

谢谢, 史蒂夫

$ _ POST示例:

Array (
    [0] => Assignment
    [1] => Assignment
    [2] => Assignment
    [3] => Assignment
    [4] => Assignment
    [5] => Assignment
    [6] => Exam
    [7] => Assignment
    [8] => Assignment
    [9] => Assignment
    [10] => Exam
    [11] => Exam
    [12] => Final Project
)
Array (
    [0] => 100
    [1] => 100
    [2] => 100
    [3] => 98
    [4] => 90
    [5] => 92
    [6] => 100
    [7] => 100
    [8] => 100
    [9] => 100
    [10] => 100
    [11] => 92
    [12] => 100
)

1 个答案:

答案 0 :(得分:0)

有几种方法可以解决这个问题,其中之一是:

// create arrays
$cat = array(
    "Assignment", "Assignment", "Assignment", 
    "Assignment", "Assignment", "Assignment", 
    "Exam", "Assignment", "Assignment", 
    "Assignment", "Exam", "Exam", "Final Project");

$grade = array(100,100,100,98,90,92,100,100,100,100,100,92,100);

// create $result: key = cat, values = sum, count, avg = 0
$result = array_fill_keys($cat, array('sum' => 0, 'count' => 0, 'avg' => 0));

$max = count($cat);

// add grades to category in $result[cat][sum]
for ($i = 0; $i < $max; $i++) 
   $result[$cat[$i]]['sum'] += $grade[$i];

// count number of categories in $cat
$num = array_count_values($cat);

// fill $result[cat][count]...
// then divide each cat's sum by each cat's count => $result[cat][avg]
foreach ($result as $k => $v) {
    $result[$k]['count'] = $num[$k];
    $result[$k]['avg'] = round($result[$k]['sum'] / $num[$k], 2);
}

结果:

Array
(
    [Assignment] => Array
        (
            [sum] => 880
            [count] => 9
            [avg] => 97.78
        )

    [Exam] => Array
        (
            [sum] => 292
            [count] => 3
            [avg] => 97.33
        )

    [Final Project] => Array
        (
            [sum] => 100
            [count] => 1
            [avg] => 100
        )

)

看到它有效:http://codepad.viper-7.com/QQAaXD