从PHP中的多维数组中查找平均值

时间:2014-08-28 22:59:33

标签: php for-loop multidimensional-array

我有一个看起来像这样的数组(以及指定的值):

loop thru students {
     $count = 0;
     loop thru classes { 
          $myArr[$obj->student][$count] = $grade;
     }
}

我在表格中有数据:沿顶部标题是类。沿着sides是学生。每个交叉引用的单元格是学生成绩。我希望底部行成为班上所有学生的平均成绩。

我在上面的数组中有我需要的信息(第一部分是学生ID,第二部分是多少课程的数量:总是相同的。

我正在努力解决的问题是提取我需要的信息以获得平均值:

我基本上需要先通过SECOND部分循环,以获得学生总数和平均成绩。我不确定我是按照数组的顺序做这个最好的方法。但这是重要的信息:外部循环是学生,内部循环是类:这就是为什么我选择了我使用的顺序。

有人可以帮助我走上正轨吗?开始似乎是微不足道的。

修改 - 按要求添加数据:

样本数据;学生证和成绩; (有些成绩是空白但请忽略并假设它们将被填补;我将处理这些成绩)

  [18273372] => Array
        (
            [0] => 40%
            [1] => 50%
            [2] => 100%
            [3] => 20%
            [4] => ---
            [5] => ---
            [6] => ---
            [7] => ---
            [8] => ---
            [9] => ---
            [10] => ---
            [11] => ---
            [12] => 50%
            [13] => ---
            [14] => ---
            [15] => ---
        )



 [18273372] => Array
        (
            [0] => 50%
            [1] => 50%
            [2] => 100%
            [3] => 50%
            [4] => ---
            [5] => ---
            [6] => ---
            [7] => 55%
            [8] => ---
            [9] => 70%
            [10] => ---
            [11] => ---
            [12] => 50%
            [13] => ---
            [14] => ---
            [15] => ---
        )

我需要平均值;例如,位置(或类别)0平均为45%。同样,0 - 15代表16个不同的类。每个学生的0级是相同的。

编辑:

这是我的更新程序代码:

$avg[$obj->s_i_student_num][$count] = $gradebook->unitPercentage[$count];
                $totals = array();
                foreach($avg as $student_id => $scores) {
                      foreach($scores as $id => $percent) {

                            if ($percent == "---") { continue; } 

                            $percent = (int) $percent;
                            $totals[$id][] = $percent;

                      }
                }

1 个答案:

答案 0 :(得分:2)

这是一种方法:遍历结果并将每个百分比按键保存到临时数组中,将它们组合在一起:

$totals = array();

foreach($test_data as $student_id => $scores) {
  foreach($scores as $id => $percent) {
    // Trim off the percent sign  
    $percent = (int) $percent;
    // Initialize array key if it's the first time
    if(!array_key_exists($id, $totals))
      $totals[$id] = array();
    $totals[$id][] = $percent;
  }
}

然后,对该数组运行一次​​传递以按键平均所有结果,并重新添加百分号:

// Affect original: pass variable by reference (&)
array_walk($totals, function(&$value) {
  // Sum values, divide by the size of the array (average) then add % on
  $value = array_sum($value) / count($value) . '%';
});

print_r($totals)显示:

Array
(
    [0] => 45%
    [1] => 50%
    [2] => 100%
    [3] => 35%
    [12] => 50%
    [7] => 55%
    [9] => 70%
)

键是每个数组中原始分数的关键。 Demo.