【PHP】统计问卷调查结果的选项票数和百分比

遇到问题:

有以下数组,每一条记录是用户的每一条问卷题目的回答情况,q_id是问题id,o_id是选项id。需要统计每一个选项被选择的次数和每个选项占该问题的百分比。如问题1的选项有A和B,一个用户选择了A之后,则问题1A选项是1票占比100%,问题1B选项是0票占比0%。

array(49) {
  [0] => array(2) {
    ["q_id"] => string(2) "57"
    ["o_id"] => string(3) "125"
  }
  [1] => array(2) {
    ["q_id"] => string(2) "58"
    ["o_id"] => string(3) "129"
  }
  [2] => array(2) {
    ["q_id"] => string(2) "59"
    ["o_id"] => string(3) "131"
  }
  [3] => array(2) {
    ["q_id"] => string(2) "65"
    ["o_id"] => string(3) "145"
  }
  [4] => array(2) {
    ["q_id"] => string(2) "57"
    ["o_id"] => string(3) "126"
  }
  [5] => array(2) {
    ["q_id"] => string(2) "58"
    ["o_id"] => string(3) "130"
  }
}

 

解决方法:

需要用到array_count_values()函数,详情可参考http://www.w3school.com.cn/php/func_array_count_values.asp

$oCount = array_count_values(array_column($aList,'o_id'));//统计选项
$qCount = array_count_values(array_column($aList,'q_id'));//统计该问题总共选项
$oCount数组如下,记录每个选项被选择次数。
array(18) {
  [125] => int(3)
  [129] => int(1)
  [131] => int(3)
  [145] => int(3)
  [126] => int(2)
  [130] => int(6)
}
$qCount数组如下,记录每道题下面的被回答次数。
array(8) {
  [57] => int(9)
  [58] => int(7)
  [59] => int(6)
  [65] => int(7)
  [64] => int(5)
  [66] => int(5)
  [67] => int(5)
  [68] => int(5)
}

然后需要联系到每个选项的父id,即问题id

        foreach ($oCount as $k => $v){
           //$q_id为该选项所属的问题id
            $q_id = M('h1_answer as a')
                -> join('by_h1_option as o on o.id = a.o_id')
                -> where('o.id='.$k)
                -> getField('q_id');
            $count[$k] = [
                'num'       =>  $v,//票数
                'persent'   =>  round($v/$qCount[$q_id]*100,2)//统计百分比
            ];
        }    

打印结果,就可以得到每个选项的票数和占题目百分比了

  [125] => array(2) {
    ["num"] => int(3)
    ["persent"] => float(33.33)
  }
  [129] => array(2) {
    ["num"] => int(1)
    ["persent"] => float(14.29)
  }
  [131] => array(2) {
    ["num"] => int(3)
    ["persent"] => float(50)
  }
  [145] => array(2) {
    ["num"] => int(3)
    ["persent"] => float(42.86)
  }
  [126] => array(2) {
    ["num"] => int(2)
    ["persent"] => float(22.22)
  }
  [130] => array(2) {
    ["num"] => int(6)
    ["persent"] => float(85.71)
  }

 

posted @ 2019-04-10 17:26  李文和  阅读(1013)  评论(0编辑  收藏  举报