0

我对 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
)
4

1 回答 1

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

于 2013-04-28T21:16:11.590 回答