I have tried the following way; but can it be done in any other way?
<?php
$arr = array(
"text"=>"1,1,1,1,1,1,3,4,4,4,2,2,4,3,5,5,5,5,5,5,5,5,2,4,3,3,2,3,3,3,4,3,3,3,3,3,3,3,3,4,1,4,1,1,4,2,2,2,2,3"
);
foreach( $arr as $question=>$answer ) {
$ext = ((Integer)$answer[0] (Integer)$answer[2] (Integer)$answer[4] (Integer)$answer[6] (Integer)$answer[8] (Integer)$answer[10] (Integer)$answer[12] (Integer)$answer[14] (Integer)$answer[16] (Integer)$answer[18])/10.0;
$est = ((Integer)$answer[20] (Integer)$answer[22] (Integer)$answer[24] (Integer)$answer[26] (Integer)$answer[28] (Integer)$answer[30] (Integer)$answer[32] (Integer)$answer[34] (Integer)$answer[36] (Integer)$answer[38])/10.0;
$agr = ((Integer)$answer[40] (Integer)$answer[42] (Integer)$answer[44] (Integer)$answer[46] (Integer)$answer[48] (Integer)$answer[50] (Integer)$answer[52] (Integer)$answer[54] (Integer)$answer[56] (Integer)$answer[58])/10.0;
$csn = ((Integer)$answer[60] (Integer)$answer[62] (Integer)$answer[64] (Integer)$answer[66] (Integer)$answer[68] (Integer)$answer[70] (Integer)$answer[72] (Integer)$answer[74] (Integer)$answer[76] (Integer)$answer[78])/10.0;
$opn = ((Integer)$answer[80] (Integer)$answer[82] (Integer)$answer[84] (Integer)$answer[86] (Integer)$answer[88] (Integer)$answer[90] (Integer)$answer[92] (Integer)$answer[94] (Integer)$answer[96] (Integer)$answer[98])/10.0;
echo($ext);
echo("\n");
echo($est);
echo("\n");
echo($agr);
echo("\n");
echo($csn);
echo("\n");
echo($opn);
}
?>
I am calculating ext by adding elements of $arr[0:9] and then calculating its average
I am calculating est by adding elements of $arr[10:19] and then calculating its average
I am calculating agr by adding elements of $arr[20:29] and then calculating its average
I am calculating csn by adding elements of $arr[30:39] and then calculating its average
I am calculating opn by adding elements of $arr[40:49] and then calculating its average
The output is coming in the following manner:
2.1
4.1
3.3
3.2
2.2
CodePudding user response:
Use explode to create an actual array out of your comma-separated values first, divide that into chunks of 10 values each, and then calculate the average for those.
$data = array_chunk(explode(',', $arr['text']), 10);
foreach($data as $datum) {
echo array_sum($datum) / count($datum), "<br>\n";
}