计算每条记录的票数百分比。

时间:2014-03-10 15:39:42

标签: php

我搜索了这个网站和谷歌,我无法弄清楚

<?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";
}   


?>

如何从表格中回显出每张唱片的总票数百分比?

1 个答案:

答案 0 :(得分:1)

首先,我将获得变量中的总票数,然后在下一个中用于检查总票数是否大于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";
}