Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Apr 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Add a total in a PHP Scoreboard

    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

  • #2
    Regular Coder
    Join Date
    Sep 2011
    Posts
    213
    Thanks
    15
    Thanked 5 Times in 5 Posts
    Quote Originally Posted by colin1996 View Post
    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.
    PHP Code:
    $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
    PHP Code:
    foreach($scores as $i => $arr
    Last edited by Dubz; 04-18-2012 at 11:29 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •