php项目统计射门次数哪队更多?

wen PHP项目 2

本文目录导读:

php项目统计射门次数哪队更多?

  1. 方案一:简单的函数实现
  2. 方案二:数据库存储(假设使用MySQL)
  3. 方案三:API接口形式
  4. 使用建议

我可以帮你设计一个PHP项目来统计两队射门次数并比较哪队更多,这里有几种实现方案:

简单的函数实现

<?php
class ShotStatistic {
    private $teamAShots = [];
    private $teamBShots = [];
    // 记录射门
    public function addShot($team, $isOnTarget = true, $minute = null) {
        $shot = [
            'is_on_target' => $isOnTarget,
            'minute' => $minute ?? date('i:s')
        ];
        if (strtoupper($team) === 'A') {
            $this->teamAShots[] = $shot;
        } else {
            $this->teamBShots[] = $shot;
        }
    }
    // 获取总射门数
    public function getTotalShots($team) {
        return strtoupper($team) === 'A' 
            ? count($this->teamAShots) 
            : count($this->teamBShots);
    }
    // 比较射门次数
    public function compareShots() {
        $countA = count($this->teamAShots);
        $countB = count($this->teamBShots);
        if ($countA > $countB) {
            return "A队射门更多";
        } elseif ($countB > $countA) {
            return "B队射门更多";
        } else {
            return "双方射门次数相同";
        }
    }
    // 获取详细统计
    public function getStatistics() {
        return [
            'teamA' => [
                'total_shots' => count($this->teamAShots),
                'shots_on_target' => count(array_filter($this->teamAShots, fn($s) => $s['is_on_target']))
            ],
            'teamB' => [
                'total_shots' => count($this->teamBShots),
                'shots_on_target' => count(array_filter($this->teamBShots, fn($s) => $s['is_on_target']))
            ]
        ];
    }
}
// 使用示例
$stats = new ShotStatistic();
// 模拟A队射门
$stats->addShot('A', true, 12);
$stats->addShot('A', false, 23);
$stats->addShot('A', true, 34);
// 模拟B队射门
$stats->addShot('B', true, 15);
$stats->addShot('B', false, 28);
echo "A队射门: " . $stats->getTotalShots('A') . "次\n";
echo "B队射门: " . $stats->getTotalShots('B') . "次\n";
echo "结果: " . $stats->compareShots() . "\n";
print_r($stats->getStatistics());
?>

数据库存储(假设使用MySQL)

<?php
class MatchShotTracker {
    private $pdo;
    public function __construct($host, $dbname, $user, $pass) {
        try {
            $this->pdo = new PDO(
                "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
                $user,
                $pass,
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
            $this->createTables();
        } catch (PDOException $e) {
            die("数据库连接失败: " . $e->getMessage());
        }
    }
    private function createTables() {
        $sql = "
            CREATE TABLE IF NOT EXISTS matches (
                id INT PRIMARY KEY AUTO_INCREMENT,
                match_date DATETIME,
                home_team VARCHAR(100),
                away_team VARCHAR(100)
            );
            CREATE TABLE IF NOT EXISTS shots (
                id INT PRIMARY KEY AUTO_INCREMENT,
                match_id INT,
                team_name VARCHAR(100),
                shoot_time TIME,
                is_on_target BOOLEAN,
                FOREIGN KEY (match_id) REFERENCES matches(id)
            );
        ";
        $this->pdo->exec($sql);
    }
    public function addMatch($homeTeam, $awayTeam) {
        $stmt = $this->pdo->prepare("INSERT INTO matches (match_date, home_team, away_team) VALUES (NOW(), ?, ?)");
        $stmt->execute([$homeTeam, $awayTeam]);
        return $this->pdo->lastInsertId();
    }
    public function recordShot($matchId, $teamName, $isOnTarget = true) {
        $stmt = $this->pdo->prepare("INSERT INTO shots (match_id, team_name, shoot_time, is_on_target) VALUES (?, ?, NOW(), ?)");
        return $stmt->execute([$matchId, $teamName, $isOnTarget]);
    }
    public function compareShots($matchId) {
        $sql = "
            SELECT 
                team_name,
                COUNT(*) as total_shots,
                SUM(CASE WHEN is_on_target = 1 THEN 1 ELSE 0 END) as shots_on_target
            FROM shots 
            WHERE match_id = ?
            GROUP BY team_name
            ORDER BY total_shots DESC
        ";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$matchId]);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $output = [];
        foreach ($results as $row) {
            $output[] = "{$row['team_name']}: 总射门 {$row['total_shots']}次, 射正 {$row['shots_on_target']}次";
        }
        if (count($results) == 2) {
            $output[] = $results[0]['total_shots'] > $results[1]['total_shots'] 
                ? "{$results[0]['team_name']}射门更多" 
                : ($results[0]['total_shots'] < $results[1]['total_shots'] 
                    ? "{$results[1]['team_name']}射门更多" 
                    : "双方射门次数相同");
        }
        return $output;
    }
}
// 使用示例
$tracker = new MatchShotTracker('localhost', 'football_db', 'username', 'password');
// 创建比赛
$matchId = $tracker->addMatch('巴塞罗那', '皇家马德里');
// 记录射门(模拟数据)
$tracker->recordShot($matchId, '巴塞罗那', true);
$tracker->recordShot($matchId, '巴塞罗那', false);
$tracker->recordShot($matchId, '皇家马德里', true);
$tracker->recordShot($matchId, '皇家马德里', true);
$tracker->recordShot($matchId, '皇家马德里', false);
// 比较结果
$result = $tracker->compareShots($matchId);
foreach ($result as $line) {
    echo $line . "\n";
}
?>

API接口形式

<?php
header('Content-Type: application/json');
class ShotAPI {
    private $matchData = [];
    public function receiveData($teamName, $shotType) {
        $event = [
            'team' => $teamName,
            'type' => $shotType,
            'time' => date('Y-m-d H:i:s')
        ];
        $this->matchData[] = $event;
        return $event;
    }
    public function getSummary() {
        $teams = [];
        foreach ($this->matchData as $event) {
            $team = $event['team'];
            if (!isset($teams[$team])) {
                $teams[$team] = ['total' => 0, 'on_target' => 0];
            }
            $teams[$team]['total']++;
            if ($event['type'] == 'on_target') {
                $teams[$team]['on_target']++;
            }
        }
        // 找出射门最多的队
        if (empty($teams)) {
            return json_encode(['message' => '暂无射门数据']);
        }
        $maxShots = max(array_column($teams, 'total'));
        $leaderBoard = [];
        foreach ($teams as $team => $stats) {
            $leaderBoard[] = [
                'team' => $team,
                'total_shots' => $stats['total'],
                'on_target' => $stats['on_target'],
                'is_leader' => $stats['total'] == $maxShots
            ];
        }
        return json_encode([
            'date' => date('Y-m-d'),
            'stats' => $leaderBoard,
            'most_shots' => $maxShots,
            'message' => count(array_filter($leaderBoard, fn($t) => $t['is_leader'])) > 1 
                ? '并列第一' 
                : '射门最多的球队'
        ]);
    }
}
// 路由处理
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $api = new ShotAPI();
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'record':
                $result = $api->receiveData($_POST['team'], $_POST['type']);
                echo json_encode(['status' => 'success', 'data' => $result]);
                break;
            case 'summary':
                echo $api->getSummary();
                break;
            default:
                echo json_encode(['error' => '未知操作']);
        }
    }
}
?>

使用建议

  1. 小型项目:使用方案一,简单直接
  2. 需要持久化存储:使用方案二,支持历史数据查询
  3. 前后端分离:使用方案三作为API接口

你可以根据需求选择适合的方案,需要我详细解释某个特定部分吗?

抱歉,评论功能暂时关闭!