Reputation: 45
For example I have a mysql_num_rows results of 4,8,15,16,23,42 in a query that is inside a while loop of another query. My question is how can I get the percentage per each result of mysql_num_rows inside my while loop? Example: 4,8,15,16,23,42. Total is 108. $sum = 108. Percentage of 4 = 4/$sum = 3.7%, 8 = 8/$sum = 7.4% and so on..
Upvotes: 0
Views: 1224
Reputation: 11711
So you are saying that you want the $sum before the individual results right? You could do a simple additional query to get the sum before you pull out the individual results. Use the SUM aggregate function. It is probably also possible to get the percentage in your SQL results. That would mean a slightly more complex query, but not an additional query.
Upvotes: 0
Reputation: 490413
$values = array(4, 8, 15, ...);
$sum = array_sum($values);
foreach($values as $value) {
echo ($value / $sum) * 100;
}
Upvotes: 0
Reputation: 10214
you can store all the values in an array and do the calcs after you have retrieved the data from the database
eg
$datastore = array();
$total = 0;
while(list($amount) = mysql_fetch_row($result)) {
$datastore[] = $amount;
$total += $amount;
}
foreach ($datastore as $amount) {
echo $amount," - ";
printf("%5.2f", $amount/$total);
echo "\r\n";
}
Upvotes: 1