计算百分比误差

时间:2016-03-02 20:37:52

标签: php jquery jquery-calculation

我正在尝试修复这个百分比计算,但今天它只是让我感到难过。

以下是代码:

$entries = GFAPI::get_entries($form['id'], $search_criteria);

$score = 0;
$max = 0;
$percentage = array();
if(!empty($entries)) {
    foreach ($entries as $entry) {

        $score = GFSurvey::get_field_score($form_fields, $entry);
        $max = end($form_fields['choices']);

        if(empty($max['score'])) {
            unset($form_fields['choices'][key($form_fields['choices'])]);
            $max = end($form_fields['choices']);
            }
        $max = $max['score'];
        $percentage[] = ($score / $max ) * 100;
        }
    }

$average = round(array_sum($percentage) / count($percentage), 2);

我有表格,表格上有“不适用”单选按钮。当客户填写表格时,有时在某些问题上他们需要是N / A,因为它们不适用,并且不需要计入总体总分。

这是生成的报告,其中%不正确。该百分比应为:94%。在这张图片中,您将看到如果单击图表,您可以看到:

Graph Once Clicked

它显示的是回答此问题的人,并且有20个。每个人总共有5个最大积分,或者在这种情况下,我将N / A框设置为空白,返回0。它正在做的是总计所有可能的点数为100.(20个人和5个最大点)

我需要它做的是计算空白字段,作为回报,我在图片Graph Once Clicked中给出了例子,只有5个人回答,所以最高分为25。总分为23.5,所以23.5 / 25.

1 个答案:

答案 0 :(得分:0)

这段代码怎么样?已回答问题的总百分比在变量$total_percentage中。

$entries = GFAPI::get_entries($form['id'], $search_criteria);

$score = 0;
$max = 0;
$total_max = $total_score = 0;
$percentage = array();
if(!empty($entries)) {
    foreach ($entries as $entry) {

        $score = GFSurvey::get_field_score($form_fields, $entry);
        $max = end($form_fields['choices']);

        if(empty($max['score'])) {
            unset($form_fields['choices'][key($form_fields['choices'])]);
            $max = end($form_fields['choices']);
            }
        $max = $max['score'];

        if ($max) {
            $total_score += $score;
            $total_max += $max;
        }

        $percentage[] = ($score / $max ) * 100;
        }
    }

$average = round(array_sum($percentage) / count($percentage), 2);
$total_percentage = ($total_max > 0) ? round($total_score/$total_max/100, 2) : 0;