...

View Full Version : Add a total in a PHP Scoreboard



colin1996
04-18-2012, 10:52 AM
Hi All
Newbie question.

I'm trying to add a total of the $scores in a scoreboard at the bottom of the table.

Can anyone help please ?

This is what i have so far
[CODE]
function leaderboard()
{
$scores = get_scores();
$num_scores = count( $scores );
usort( $scores, 'cmp_scores' );

$HTML = '<table id="entries">' . "\n";
$HTML .= '<thead>' . "\n";
$HTML .= '<tr>' . "\n";
$HTML .= ' <th>BDM</th>' . "\n";
$HTML .= ' <th>Attendees</th>' . "\n";
$HTML .= '</tr>' . "\n";
$HTML .= '</thead>' . "\n";
$HTML .= '<tbody>' . "\n";

for ( $i = 0; $i < $num_scores; $i++ )
{
$HTML .= '<tr>' . "\n";
$HTML .= ' <td class="player">' . str_format( $scores[$i]['name'] ) . '</td>' . "\n";
$HTML .= ' <td class="player">' . $scores[$i]['points'] . '</td>' . "\n";
$HTML .= '</tr>' . "\n";
}

$HTML .= '</tbody>' . "\n";

$HTML .= '<tfoot>' . "\n";
$HTML .= '<tr>' . "\n";
$HTML .= ' <th colspan="2"></th>' . "\n";
$HTML .= '</tr>' . "\n";
$HTML .= '</tfoot>' . "\n";

$HTML .= '</table>' . "\n";

return $HTML;
[CODE]

Everything functions beautifully - apart from the total I need to show in the 'tfoot' section.

Thanks in advance
:D

Dubz
04-19-2012, 12:27 AM
for ( $i = 0; $i < $num_scores; $i++ )
{
$HTML .= '<tr>' . "\n";
$HTML .= ' <td class="player">' . str_format( $scores[$i]['name'] ) . '</td>' . "\n";
$HTML .= ' <td class="player">' . $scores[$i]['points'] . '</td>' . "\n";
$HTML .= '</tr>' . "\n";
}

Instead of using for, try using foreach. It's designed to split an array and run through each value once.


$totalScore = 0;
foreach($scores as $arr)
{
$totalScore += $arr['points']; //This will get you your total if your lookng for the total of all the users combined
$HTML .= '<tr>' . "\n";
$HTML .= ' <td class="player">' . str_format( $arr['name'] ) . '</td>' . "\n";
$HTML .= ' <td class="player">' . $arr['points'] . '</td>' . "\n";
$HTML .= '</tr>' . "\n";
}

If you get an error with the foreach try something like this in place of it


foreach($scores as $i => $arr)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum