Skip to main content

Get Tournament Data

The get tournament data method retrieves detailed information about a specific tournament, including participant rankings, scores, and tournament progress. This is useful for displaying tournament leaderboards and player standings.

Overview

The getTournamentData method:

  • Retrieves detailed tournament information including rankings
  • Supports pagination for large tournaments
  • Returns tournament metadata and participant data
  • Provides score history and tournament statistics

Method Signature

public function getTournamentData(
string $gameID,
String $tournamentID,
int $collectionType = 1,
int $maxResults = 20,
int $page = 0
): array

Parameters

Required Parameters

  • gameID (String) - The Game ID for the tournament
  • tournamentID (String) - The Tournament ID to retrieve data for

Optional Parameters

  • collectionType (int) - Type of data to collect

    • Default: 1
    • Options: 1 (current rankings), 2 (historical data)
  • maxResults (int) - Maximum number of results per page

    • Default: 20
    • Range: 1 to 100
  • page (int) - Page number for pagination

    • Default: 0
    • Starts from 0

Return Value

Returns an array containing:

  • Tournament metadata - Tournament details and settings
  • Participant rankings - Player scores and positions
  • Tournament statistics - Participation and scoring data
  • Pagination info - Total results and current page

Basic Usage

Get Basic Tournament Data

use Veniso\Moitribe\Sdk\modules\classes\MoitribeApi;

$moitribe = new MoitribeApi([
'gameid' => 'your-game-id',
'channelid' => 'your-channel-id',
'playerid' => 'player-123'
]);

try {
$tournamentData = $moitribe->tournRequestsHandler->getTournamentData(
'your-game-id',
'tournament-123'
);

echo "Tournament Data:\n";
echo "Name: " . $tournamentData['tournament']->getName() . "\n";
echo "Participants: " . $tournamentData['participant_count'] . "\n";
echo "Current Rankings:\n";

foreach ($tournamentData['rankings'] as $index => $player) {
echo ($index + 1) . ". " . $player->getName() . " - Score: " . $player->getScore() . "\n";
}

} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}

Get Paginated Tournament Data

function getTournamentRankings($gameId, $tournamentId, $page = 0, $pageSize = 50) {
global $moitribe;

try {
$data = $moitribe->tournRequestsHandler->getTournamentData(
$gameId,
$tournamentId,
1, // collection type for current rankings
$pageSize,
$page
);

return [
'success' => true,
'rankings' => $data['rankings'] ?? [],
'total_participants' => $data['total_participants'] ?? 0,
'current_page' => $page,
'page_size' => $pageSize,
'total_pages' => ceil(($data['total_participants'] ?? 0) / $pageSize)
];

} catch (Exception $e) {
error_log("Error getting tournament data: " . $e->getMessage());
return ['success' => false, 'error' => $e->getMessage()];
}
}

// Usage
$page = isset($_GET['page']) ? (int)$_GET['page'] : 0;
$result = getTournamentRankings('your-game-id', 'tournament-123', $page);

if ($result['success']) {
echo "Page " . ($result['current_page'] + 1) . " of " . $result['total_pages'] . "\n";
echo "Total participants: " . $result['total_participants'] . "\n";

foreach ($result['rankings'] as $index => $player) {
$rank = ($result['current_page'] * $result['page_size']) + $index + 1;
echo "$rank. " . $player->getName() . " - " . $player->getScore() . "\n";
}
}

Integration Examples

Tournament Leaderboard Display

function displayTournamentLeaderboard($gameId, $tournamentId) {
global $moitribe;

try {
$data = $moitribe->tournRequestsHandler->getTournamentData(
$gameId,
$tournamentId,
1, // current rankings
100, // show top 100
0 // first page
);

if (empty($data['rankings'])) {
echo "<p>No participants yet in this tournament.</p>";
return;
}

$tournament = $data['tournament'];

echo "<div class='tournament-leaderboard'>";
echo "<h2>" . htmlspecialchars($tournament->getName()) . "</h2>";
echo "<div class='tournament-info'>";
echo "<span>Participants: " . $data['participant_count'] . "</span>";
echo "<span>End Date: " . date('M j, Y', strtotime($tournament->getEndDate())) . "</span>";
echo "</div>";

echo "<table class='leaderboard-table'>";
echo "<thead><tr>";
echo "<th>Rank</th><th>Player</th><th>Score</th><th>Prize</th>";
echo "</tr></thead>";
echo "<tbody>";

foreach ($data['rankings'] as $index => $player) {
$rank = $index + 1;
$prizeClass = $rank <= 3 ? 'prize-winner' : '';
$rankClass = $rank <= 10 ? 'top-10' : '';

echo "<tr class='$rankClass $prizeClass'>";
echo "<td class='rank'>$rank</td>";
echo "<td class='player'>" . htmlspecialchars($player->getName()) . "</td>";
echo "<td class='score'>" . number_format($player->getScore()) . "</td>";
echo "<td class='prize'>" . ($player->getPrize() ?: '-') . "</td>";
echo "</tr>";
}

echo "</tbody></table>";
echo "</div>";

} catch (Exception $e) {
echo "<div class='error'>Failed to load tournament data. Please try again later.</div>";
error_log("Tournament data error: " . $e->getMessage());
}
}

// Display on your page
displayTournamentLeaderboard('your-game-id', 'tournament-123');

Player Tournament Status

function getPlayerTournamentStatus($gameId, $tournamentId, $playerId) {
global $moitribe;

try {
$data = $moitribe->tournRequestsHandler->getTournamentData(
$gameId,
$tournamentId,
1, // current rankings
1000, // get many results to find player
0
);

$tournament = $data['tournament'];
$playerRanking = null;

// Find player in rankings
foreach ($data['rankings'] as $index => $player) {
if ($player->getId() === $playerId) {
$playerRanking = [
'rank' => $index + 1,
'player' => $player,
'score' => $player->getScore(),
'prize' => $player->getPrize()
];
break;
}
}

return [
'tournament_name' => $tournament->getName(),
'tournament_status' => $tournament->getStatus(),
'end_date' => $tournament->getEndDate(),
'total_participants' => $data['participant_count'],
'is_participating' => $playerRanking !== null,
'player_ranking' => $playerRanking,
'time_remaining' => strtotime($tournament->getEndDate()) - time()
];

} catch (Exception $e) {
error_log("Error getting player tournament status: " . $e->getMessage());
return null;
}
}

// Usage
$status = getPlayerTournamentStatus('your-game-id', 'tournament-123', 'player-456');

if ($status) {
echo "Tournament: " . $status['tournament_name'] . "\n";
echo "Status: " . $status['tournament_status'] . "\n";

if ($status['is_participating']) {
$ranking = $status['player_ranking'];
echo "Your Rank: " . $ranking['rank'] . "\n";
echo "Your Score: " . $ranking['score'] . "\n";

if ($ranking['prize']) {
echo "Current Prize: " . $ranking['prize'] . "\n";
}
} else {
echo "You haven't joined this tournament yet.\n";
}

if ($status['time_remaining'] > 0) {
$hours = floor($status['time_remaining'] / 3600);
echo "Time remaining: $hours hours\n";
}
}

Tournament Analytics Dashboard

function getTournamentAnalytics($gameId, $tournamentId) {
global $moitribe;

try {
$data = $moitribe->tournRequestsHandler->getTournamentData(
$gameId,
$tournamentId,
1, // current rankings
1000, // large sample for analytics
0
);

$tournament = $data['tournament'];
$rankings = $data['rankings'];

if (empty($rankings)) {
return ['error' => 'No data available'];
}

// Calculate analytics
$scores = array_column($rankings, 'score');
$totalParticipants = count($rankings);
$averageScore = array_sum($scores) / $totalParticipants;
$highScore = max($scores);
$lowScore = min($scores);

// Score distribution
$scoreRanges = [
'0-100' => 0, '101-500' => 0, '501-1000' => 0,
'1001-5000' => 0, '5001+' => 0
];

foreach ($scores as $score) {
if ($score <= 100) $scoreRanges['0-100']++;
elseif ($score <= 500) $scoreRanges['101-500']++;
elseif ($score <= 1000) $scoreRanges['501-1000']++;
elseif ($score <= 5000) $scoreRanges['1001-5000']++;
else $scoreRanges['5001+']++;
}

return [
'tournament_name' => $tournament->getName(),
'total_participants' => $totalParticipants,
'average_score' => round($averageScore, 2),
'highest_score' => $highScore,
'lowest_score' => $lowScore,
'score_distribution' => $scoreRanges,
'top_10_cutoff' => $rankings[9]->getScore() ?? 0,
'top_100_cutoff' => $rankings[99]->getScore() ?? 0
];

} catch (Exception $e) {
error_log("Tournament analytics error: " . $e->getMessage());
return ['error' => 'Failed to get analytics'];
}
}

// Usage
$analytics = getTournamentAnalytics('your-game-id', 'tournament-123');

if (!isset($analytics['error'])) {
echo "Tournament Analytics for: " . $analytics['tournament_name'] . "\n";
echo "Total Participants: " . $analytics['total_participants'] . "\n";
echo "Average Score: " . $analytics['average_score'] . "\n";
echo "Highest Score: " . $analytics['highest_score'] . "\n";
echo "Top 10 Cutoff: " . $analytics['top_10_cutoff'] . "\n";
}

Error Handling

Common Error Scenarios

  • Invalid tournament ID - Tournament doesn't exist
  • Invalid game ID - Game doesn't exist
  • Access denied - No permission to view tournament data
  • Tournament not started - Tournament hasn't begun yet
  • Pagination errors - Invalid page or page size parameters

Error Handling Example

function safeGetTournamentData($gameId, $tournamentId, $page = 0, $pageSize = 20) {
global $moitribe;

try {
if (empty($gameId) || empty($tournamentId)) {
throw new InvalidArgumentException("Game ID and Tournament ID are required");
}

if ($page < 0 || $pageSize < 1 || $pageSize > 100) {
throw new InvalidArgumentException("Invalid pagination parameters");
}

$data = $moitribe->tournRequestsHandler->getTournamentData(
$gameId,
$tournamentId,
1,
$pageSize,
$page
);

return [
'success' => true,
'data' => $data
];

} catch (InvalidArgumentException $e) {
return [
'success' => false,
'error' => 'Invalid input: ' . $e->getMessage()
];
} catch (Exception $e) {
error_log("Tournament data API error: " . $e->getMessage());
return [
'success' => false,
'error' => 'Failed to retrieve tournament data'
];
}
}

Best Practices

  1. Implement Pagination

    • Use pagination for tournaments with many participants
    • Show reasonable page sizes (20-50 results)
    • Provide navigation between pages
  2. Cache Tournament Data

    • Tournament data changes frequently during active periods
    • Cache for short periods (1-5 minutes)
    • Invalidate cache when new scores are submitted
  3. Handle Large Datasets

    • Use pagination to avoid memory issues
    • Consider background processing for analytics
    • Implement progressive loading for large leaderboards
  4. Display Rankings Efficiently

    • Show top rankings prominently
    • Highlight prize winners
    • Provide search/filter for large participant lists