skrafft74 Posted April 28, 2013 Share Posted April 28, 2013 I'm fairly new to PHP and trying to sort a class project. I've banged away and can't see to sort it out, this is the last remaining piece. I have a form - submit essentially 2 arrays I'm trying to determine the average score for based upon the category groupings. 1. ($_post['category']), ($_post['score']) - with category being a text based array and score obviously being numbers based. How would I go about finding the average score for each category? I've tried various options to for mapping the two arrays and then trying to average the grades. I can get the total score average pretty easily, but finding a ways to do this by each category individually is tripping me up. I need to apply a weight to each category score, but that seems pretty easy once you get the above sorted. Thanks, Steve $_POST example: 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) Quote Link to comment https://forums.phpfreaks.com/topic/277397-php-calculate-score-by-category/ Share on other sites More sharing options...
akphidelt2007 Posted April 28, 2013 Share Posted April 28, 2013 (edited) I would create an array by category with the scores. Sort of like this $scores = Array('Assignment'=>Array(),'Exam'=>Array(),'Final Project'=>Array()); foreach($_POST['categories'] as $index => $category) { $scores[$category][] = $_POST['scores'][$index]; } //now you will have an array like //$scores['Assignment'] = Array('score1','score2','score3') //loop through to get the totals foreach($scores as $cat => $array) { $count = count($array); $sumOfScores = array_sum($array); $average = $count > 0 ? $sumOfScores/$count : 0; echo "Category: $cat has $count scores and an average score of $average<br>"; } Edited April 28, 2013 by akphidelt2007 Quote Link to comment https://forums.phpfreaks.com/topic/277397-php-calculate-score-by-category/#findComment-1427026 Share on other sites More sharing options...
skrafft74 Posted April 28, 2013 Author Share Posted April 28, 2013 Thanks akphidelt, that's the piece I've been trying to figure out. foreach($_POST['categories'] as $index => $category){ $scores[$category][] = $_POST['scores'][$index];} I knew I wanted to map the two arrays together, but wasn't really sure of the syntax. Quote Link to comment https://forums.phpfreaks.com/topic/277397-php-calculate-score-by-category/#findComment-1427027 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.