获取while循环中的总百分比


Getting total percentage inside while loop

例如,在另一个查询的while循环内的查询中,我有一个mysql_num_rows结果4,8,15,16,23,42。我的问题是我怎样才能得到mysql_num_rows在我的while循环中的每个结果的百分比?例子:4、8、15、16、23日,42。总共是108。$sum = 108。百分比4 = 4/$sum = 3.7%, 8 = 8/$sum = 7.4%等等

您可以将所有值存储在数组中,并在从数据库检索数据后进行计算

$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";
}
$values = array(4, 8, 15, ...);
$sum = array_sum($values);
foreach($values as $value) {
    echo ($value / $sum) * 100;
}

CodePad .

所以你说你想要$sum之前的个别结果对吗?在提取单个结果之前,您可以执行一个简单的附加查询来获取总和。使用SUM聚合函数。也可能获得SQL结果中的百分比。这将意味着一个稍微复杂的查询,但不是一个额外的查询。