caspergmf Posted January 2, 2011 Share Posted January 2, 2011 I am trying to average a string of numbers. I've tryed everything and just don't seem to get it. After a mysql query I get the result of the of answer choices numbers of a survey. Example:(commas added by me for readability) 52,52,52,52,52,52,52,52,54,54,55,55,55,56,56,56. I then convert these into a 1 through 4 value which gives me the following result string. Example:(commas added by me for readability)1,1,1,1,1,1,1,1,2,2,3,3,3,4,4,4. I would like to average this string out which would be 2.0265 [attachment deleted by admin] Quote Link to comment https://forums.phpfreaks.com/topic/223203-averaging/ Share on other sites More sharing options...
Pikachu2000 Posted January 2, 2011 Share Posted January 2, 2011 The way you appear to be going about this makes very little sense to me. Why are you not just storing the answers in the database in the correct form (i.e. as 1, 2, 3 or 4) to begin with? Then you could simply SELECT AVG(). Quote Link to comment https://forums.phpfreaks.com/topic/223203-averaging/#findComment-1153872 Share on other sites More sharing options...
sasa Posted January 3, 2011 Share Posted January 3, 2011 try <?php // connect to the database $dbLink = mysql_connect("Blah", "Blah", "blah"); if (!$dbLink) { print "Could not connect: ".mysql_error(); exit(0); } if (!mysql_select_db("answerchoice", $dbLink)) { print "Could not select database: ".mysql_error(); exit(0); } $query= "SELECT AID FROM answer WHERE (QID = 18) AND UID IN (SELECT UID FROM answer WHERE Answer = 33) ORDER BY AID ASC"; $result = mysql_query($query, $dbLink); //this query returns data base answer choice numbers (commas added by me for readability) 52,52,52,52,52,52,52,52,54,54,55,55,55,56,56,56 $i = 0; $tmp = -1; $ans = array(); while($row = mysql_fetch_array($result)){ if($row['AID'] > $tmp){ $i++; $tmp = $row['AID']; $ans[$i]=0; } $ans[$i]++; //$i now holds the answer numbers converted into a 1-4 value (commas added by me for readability)1,1,1,1,1,1,1,1,2,2,3,3,3,4,4,4 I would like to average this string which would be 2.0265 } foreach ($ans as $v => $c){ $tot += $v * $c; $cnt += $c; } if($cnt ) $ave = $tot / $cnt; else $ave = 0; echo 'average = ',$ave; ?> Quote Link to comment https://forums.phpfreaks.com/topic/223203-averaging/#findComment-1154119 Share on other sites More sharing options...
caspergmf Posted January 3, 2011 Author Share Posted January 3, 2011 I think that did it. Thank you sasa. I believe I will look into Pikachu2000 suggestion for a more streamlined solution. Quote Link to comment https://forums.phpfreaks.com/topic/223203-averaging/#findComment-1154249 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.