Skip to main content

Overview

The Metrics functions process raw session data to calculate aggregated statistics, user rankings, and game performance indicators. These are foundational functions used throughout the analytics system.

calculate_metrics()

Calculates comprehensive metrics from an array of session records.

Function Signature

function calculate_metrics($sessions)

Parameters

sessions
array
required
Array of session objects from the database. Each session should contain:
  • score (int): Session score
  • duration (int): Session duration in seconds
  • userId (int): User ID

Returns

totalSessions
int
Total count of sessions in the input array
totalScore
int
Sum of all session scores
totalDuration
int
Sum of all session durations (in seconds)
avgScore
int
Average score across all sessions (rounded to nearest integer)
avgDuration
int
Average duration across all sessions in seconds (rounded)
activeUsers
int
Count of unique users who played sessions
passRate
int
Percentage of sessions with score >= 60 (rounded to nearest integer)

Example Usage

// Get sessions and calculate metrics
$sessions = get_sessions('Acme Corp');
$metrics = calculate_metrics($sessions);

echo "Total Sessions: {$metrics['totalSessions']}\n";
echo "Average Score: {$metrics['avgScore']}\n";
echo "Pass Rate: {$metrics['passRate']}%\n";
echo "Active Users: {$metrics['activeUsers']}\n";

Response Example

{
  "totalSessions": 542,
  "totalScore": 42567,
  "totalDuration": 228420,
  "avgScore": 79,
  "avgDuration": 421,
  "activeUsers": 187,
  "passRate": 84
}
The pass rate is calculated using a 60-point threshold. Sessions with score >= 60 are considered passing.

get_user_ranking()

Generates a ranked list of top users based on total score.

Function Signature

function get_user_ranking($sessions)

Parameters

sessions
array
required
Array of session objects to analyze

Returns

Array of top 10 user statistics, sorted by total score (descending):
userId
int
User ID
totalScore
int
Sum of all scores for this user
sessionsPlayed
int
Number of sessions played by this user
totalDuration
int
Sum of all session durations for this user (in seconds)

Example Usage

$sessions = get_sessions('Acme Corp');
$topUsers = get_user_ranking($sessions);

echo "<h2>Top 10 Users Leaderboard</h2>";
foreach ($topUsers as $rank => $user) {
    $avgScore = round($user['totalScore'] / $user['sessionsPlayed']);
    echo ($rank + 1) . ". User #{$user['userId']} - ";
    echo "{$user['totalScore']} points ({$avgScore} avg) - ";
    echo "{$user['sessionsPlayed']} sessions\n";
}

Response Example

[
  {
    "userId": 145,
    "totalScore": 2847,
    "sessionsPlayed": 34,
    "totalDuration": 14280
  },
  {
    "userId": 92,
    "totalScore": 2631,
    "sessionsPlayed": 29,
    "totalDuration": 12190
  },
  {
    "userId": 203,
    "totalScore": 2509,
    "sessionsPlayed": 31,
    "totalDuration": 13420
  }
]
Only the top 10 users are returned. The function automatically limits results.

get_game_ranking()

Ranks games by total play time and aggregates performance stats.

Function Signature

function get_game_ranking($sessions)

Parameters

sessions
array
required
Array of session objects to analyze

Returns

Array of game statistics, sorted by total play time (descending):
gameId
int
Game/dilemma ID
totalPlayTime
int
Sum of all session durations for this game (in seconds)
sessionsCount
int
Number of sessions played for this game
totalScore
int
Sum of all scores for this game

Example Usage

$sessions = get_sessions();
$gameRanking = get_game_ranking($sessions);

echo "<h2>Most Played Games</h2>";
foreach (array_slice($gameRanking, 0, 5) as $rank => $game) {
    $avgTime = round($game['totalPlayTime'] / $game['sessionsCount']);
    $avgScore = round($game['totalScore'] / $game['sessionsCount']);
    
    echo ($rank + 1) . ". Game #{$game['gameId']}\n";
    echo "   Sessions: {$game['sessionsCount']}\n";
    echo "   Total Time: " . gmdate('H:i:s', $game['totalPlayTime']) . "\n";
    echo "   Avg Score: {$avgScore}\n\n";
}

Response Example

[
  {
    "gameId": 12,
    "totalPlayTime": 45680,
    "sessionsCount": 234,
    "totalScore": 18792
  },
  {
    "gameId": 7,
    "totalPlayTime": 38920,
    "sessionsCount": 198,
    "totalScore": 15234
  },
  {
    "gameId": 23,
    "totalPlayTime": 34210,
    "sessionsCount": 176,
    "totalScore": 13568
  }
]

get_filtered_sessions()

Filters an array of sessions based on multiple criteria.

Function Signature

function get_filtered_sessions($sessions, $filters = [])

Parameters

sessions
array
required
Array of session objects to filter
filters
array
default:"[]"
Filter criteria

Returns

Filtered array of sessions matching all specified criteria.

Example Usage

$allSessions = get_sessions();

// Get sessions from January 2024
$janSessions = get_filtered_sessions($allSessions, [
    'startDate' => '2024-01-01',
    'endDate' => '2024-01-31'
]);

echo "January sessions: " . count($janSessions);

Filtering Logic

  • All filters are combined with AND logic (all must match)
  • Date comparisons use strtotime() for flexibility
  • The endDate time is automatically set to 23:59:59 to include the entire day
  • Using 'all' as a filter value is equivalent to not specifying that filter

get_usage_over_time()

Aggregates session and user counts by date for trend analysis.

Function Signature

function get_usage_over_time($sessions)

Parameters

sessions
array
required
Array of session objects to analyze

Returns

Array of daily statistics, sorted by date (ascending):
date
string
Date in Y-m-d format
sessions
int
Number of sessions on this date
users
int
Number of unique users who played on this date

Example Usage

$sessions = get_sessions();
$usage = get_usage_over_time($sessions);

echo "<h2>Daily Usage Trend</h2>";
foreach ($usage as $day) {
    echo "{$day['date']}: {$day['sessions']} sessions, {$day['users']} users\n";
}

// Find peak day
$peakDay = array_reduce($usage, function($carry, $day) {
    return ($day['sessions'] > ($carry['sessions'] ?? 0)) ? $day : $carry;
});
echo "\nPeak day: {$peakDay['date']} with {$peakDay['sessions']} sessions";

Response Example

[
  {
    "date": "2024-01-15",
    "sessions": 42,
    "users": 28
  },
  {
    "date": "2024-01-16",
    "sessions": 67,
    "users": 41
  },
  {
    "date": "2024-01-17",
    "sessions": 58,
    "users": 35
  }
]
Use this function with charting libraries to create time-series visualizations of platform usage.

Performance Considerations

Memory Usage

These functions operate on in-memory arrays. For large datasets:
  • Consider pre-filtering sessions at the database level using get_sessions($client_filter)
  • Use pagination when displaying rankings
  • Cache results of expensive calculations

Calculation Efficiency

  • calculate_metrics(): O(n) - single pass through sessions
  • get_user_ranking(): O(n + m log m) where m is unique users
  • get_game_ranking(): O(n + g log g) where g is unique games
  • get_filtered_sessions(): O(n) - single pass
  • get_usage_over_time(): O(n + d log d) where d is unique dates

Best Practices

// Good: Filter early, calculate once
$clientSessions = get_sessions('Acme Corp');
$filtered = get_filtered_sessions($clientSessions, ['startDate' => '2024-01-01']);
$metrics = calculate_metrics($filtered);

// Avoid: Multiple full dataset iterations
// Instead cache intermediate results

Integration Example

Complete workflow combining multiple metrics functions:
// 1. Get base dataset
$clientFilter = 'Acme Corp';
$allSessions = get_sessions($clientFilter);

// 2. Apply time filter
$thisMonth = get_filtered_sessions($allSessions, [
    'startDate' => date('Y-m-01'),
    'endDate' => date('Y-m-t')
]);

// 3. Calculate comprehensive metrics
$metrics = calculate_metrics($thisMonth);
$topUsers = get_user_ranking($thisMonth);
$gameRanking = get_game_ranking($thisMonth);
$dailyUsage = get_usage_over_time($thisMonth);

// 4. Display dashboard
echo "Monthly Report for {$clientFilter}\n";
echo "=================================\n";
echo "Total Sessions: {$metrics['totalSessions']}\n";
echo "Active Users: {$metrics['activeUsers']}\n";
echo "Average Score: {$metrics['avgScore']}\n";
echo "Pass Rate: {$metrics['passRate']}%\n\n";

echo "Top 3 Users:\n";
foreach (array_slice($topUsers, 0, 3) as $i => $user) {
    echo ($i+1) . ". User #{$user['userId']}: {$user['totalScore']} points\n";
}

echo "\nMost Played Game: #{$gameRanking[0]['gameId']}\n";

Build docs developers (and LLMs) love