计算每个记录的投票百分比


Calculate percentage of up votes for each record.

我已经搜索了这个网站和谷歌,但我不明白

<?php
$artistname = "SELECT * from voting";
$artistnameresults = mysql_query( $artistname )
or die( "Could not get video games " .mysql_error() );
for( $i = 0; $i < mysql_numrows( $artistnameresults ); $i++ ) {
    $data = mysql_fetch_array( $artistnameresults );
    echo "<div>". $data['artist'] ." has " . $data['votes'] ." votes</div>'n";
}   

?>

如何回显表中每条记录的总投票百分比?

因此,首先我将获得变量中的总投票数,然后在接下来的for中检查总投票数是否大于0以避免错误。

$num_rows = mysql_numrows($artistnameresults);
$total_votes = 0;
$rows = array();
for( $i = 0; $i < $num_rows; $i++ ) {
    $data = mysql_fetch_array( $artistnameresults );
    $total_votes += $data['votes'];
    $row[] = $data;
}
foreach($rows as $data) {
    echo "<div>". $data['artist'] ." has " . $data['votes'] ." votes ";
    if($total_votes > 0)
        $temp_votes = $data['votes']/$total_votes;  
    else
        $temp_votes = 1;        
    echo '( '.($temp_votes*100).'%)';
    echo "</div>'n";
}