本文目录导读:

在PHP项目中,“协防补位成功次数”这个指标通常出现在足球赛事数据统计、篮球防守数据或团队协作类系统的报表模块中。
由于PHP本身是后端语言,这个“次数”通常是前端JS埋点或数据采集器上报后,由PHP后端进行统计存储的。
针对这个问题,我直接为你提供后端PHP统计该指标的核心代码思路,分为数据库统计和实时计算两种场景:
基于数据库表(最常用,假设已有事件记录表)
假设你有一张防守事件记录表 defense_actions,字段包含 player_id, action_type(如 cover/support),以及 is_success(布尔值)。
PHP统计代码(Laravel 或 ThinkPHP 框架风格):
<?php
use Illuminate\Support\Facades\DB;
/**
* 统计指定球员或全队的协防补位成功次数
* @param int|null $playerId 球员ID(传null则统计全队)
* @param string $startDate 开始日期 Y-m-d
* @param string $endDate 结束日期 Y-m-d
* @return int 成功次数
*/
function countCoverSuccess(?int $playerId, string $startDate, string $endDate): int
{
$query = DB::table('defense_actions')
->whereIn('action_type', ['cover', 'support']) // 协防或补位
->where('is_success', true) // 只算成功的
->whereBetween('created_at', [$startDate . ' 00:00:00', $endDate . ' 23:59:59']);
// 如果指定了球员
if ($playerId) {
$query->where('player_id', $playerId);
}
return $query->count(); // 直接返回COUNT(*)
}
原生SQL写法(适合非框架):
SELECT COUNT(*) AS success_count
FROM defense_actions
WHERE action_type IN ('cover', 'support')
AND is_success = 1
AND created_at BETWEEN '2023-01-01 00:00:00' AND '2023-12-31 23:59:59';
实时上报(Redis 计数器)
如果数据量极大,且实时性要求高,建议直接用 Redis 自增,避免阻塞 MySQL。
PHP(Redis 实现):
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
/**
* 记录一次协防补位成功
* @param int $playerId 球员ID
*/
function recordCoverSuccess(int $playerId): void
{
global $redis;
// 按日期存储,方便统计历史
$key = "defense:cover_success:" . $playerId . ":" . date('Ymd');
$redis->incr($key);
// 还可以设置过期时间(比如30天)
$redis->expire($key, 30 * 86400);
}
// 获取统计
function getCoverSuccessCount(int $playerId, string $dateYm): int
{
global $redis;
$key = "defense:cover_success:" . $playerId . ":" . $dateYm;
return (int)$redis->get($key);
}
内存计算(针对实时比赛流)
如果数据是通过定时任务或WebSocket推送的,可以用 PHP 内置的 array_reduce 或者遍历 Collection 来计算:
<?php
// 假设 $events 是从接口获取到的实时数据
$events = [
['type' => 'cover', 'success' => true],
['type' => 'support', 'success' => false],
['type' => 'cover', 'success' => true],
['type' => 'cover', 'success' => true],
];
$count = collect($events)
->where('success', true)
->whereIn('type', ['cover', 'support'])
->count();
echo "协防补位成功次数: " . $count; // 输出: 3
扩展:统计成功率(常用组合)
通常看板还会要求显示“成功率”,这里附带一个计算方式:
<?php
$totalActions = DB::table('defense_actions')
->whereIn('action_type', ['cover', 'support'])
->count();
$successActions = countCoverSuccess(null, '2023-01-01', '2023-12-31');
// 计算成功率(注意除数不能为0)
$rate = $totalActions > 0 ? round($successActions / $totalActions * 100, 2) : 0;
echo "成功率: {$rate}%";
重要提醒(关于字段定义)
在真实项目中,建议检查你的数据结构:
- 动作类型判断:确认你的代码里是区分“协防”(协助)和“补位”(填补空缺)的,还是统一用
interception(拦截)等字段替代。 - 成功判定:“成功”的定义是否意味着球权转换(抢断成功)还是仅仅触球解围?需要和业务方确认逻辑。
如果上述代码结构跟你项目里的不一样,可以贴出你的表结构或者模型类,我可以帮你改成直接适配你项目的代码。