PHP 和 Redis Bitmap 计算用户留存率

大数据平台崛起;靠流量转化收益必然趋势。

// 连接到 Redis 服务器
$redis = new Predis\Client();

// 用户ID
$userID = 123;

// 记录用户在某个日期活跃
function markUserActive($redis, $userID, $date)
{
    $redis->setbit("user:$userID:active_dates", $date, 1);
}

// 检查用户在某个日期是否活跃
function isUserActive($redis, $userID, $date)
{
    return $redis->getbit("user:$userID:active_dates", $date) == 1;
}

// 计算留存率
function calculateRetentionRate($redis, $endDate, $numOfDays)
{
    $activeUsers = 0;
    $totalUsers = $redis->hlen("users");  // 假设用户存储在 Redis 的 Hash 中,使用 "users" 键

    for ($i = 0; $i < $numOfDays; $i++) {
        $date = date('Y-m-d', strtotime("-$i days", strtotime($endDate)));

        // 对于每一天,检查用户是否在这一天活跃
        foreach ($redis->hkeys("users") as $userID) {
            if (isUserActive($redis, $userID, $date)) {
                $activeUsers++;
            }
        }

        // 输出每天的留存率
        $retentionRate = ($activeUsers / $totalUsers) * 100;
        echo "Retention rate on $date: $retentionRate%\n";

        $activeUsers = 0;  // 重置活跃用户计数
    }
}

// 示例:标记用户在某个日期活跃
markUserActive($redis, $userID, '2023-01-01');

// 示例:计算留存率,假设计算最近 7 天的留存率
calculateRetentionRate($redis, '2023-01-07', 7);

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值