You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2088 lines
76 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace Admin\Controller;
use Admin\Model\SpendModel;
use Open\Model\UserLoginRecordModel;
use Admin\Model\UserPlayModel;
use Base\Repository\UserRepository;
use User\Api\UserApi as UserApi;
use GuzzleHttp\Client;
/**
* 后台首页控制器
* @author 麦当苗儿 <zuojiazi@vip.qq.com>
*/
class StatController extends ThinkController
{
public function user($p=1) {
$page = intval($p);
$page = $page ? $page : 1; //默认显示第一页数据
if(isset($_REQUEST['row'])) {$row = $_REQUEST['row'];}else{$row = 10;}
if(is_numeric($_REQUEST['game_id']) && $_REQUEST['game_id']>0) {
$game_id = I('game_id','');
$gamesource = get_source_from_game($game_id);
} else {
$gamesource = '全部';
}
if(is_numeric($_REQUEST['promote_id'])) {
$promote_id = I('promote_id',0);
$promoteaccount = get_promote_name($promote_id);
} else {
$promoteaccount = '全部';
}
$list = D('user')->user($promote_id,$game_id);
$count = count($list);
$data = array_slice($list,($page-1)*$row,$row,true);
file_put_contents(RUNTIME_PATH.'/access_data_user.txt',json_encode($list));
$page = set_pagination($count,$row);
if($page) {$this->assign('_page', $page);}
$this->checkListOrCountAuthRestMap($map,[]);
$this->meta_title = '用户统计';
$this->assign('data',$data);
$this->assign('game_source',$gamesource);
$this->assign('promote_account',$promoteaccount);
$this->display();
}
public function user1($p=1) {
$page = intval($p);
$page = $page ? $page : 1; //默认显示第一页数据
if(isset($_REQUEST['row'])) {$row = $_REQUEST['row'];}else{$row = 10;}//10;
$start = $_GET['start']= I('start',date('Y-m-d',strtotime('-2 day')));
$end = I('end',date('Y-m-d',strtotime('-1 day')));
$end = strtotime($end)>=strtotime(date('Y-m-d'))?date('Y-m-d',strtotime('-1 day')):$end;
$_GET['end'] = $end;
if(is_numeric($_REQUEST['game_id']) && $_REQUEST['game_id']>0) {
$game_id = I('game_id','');
$gamesource = get_source_from_game($game_id);
} else {
$gamesource = '全部';
}
if(is_numeric($_REQUEST['promote_id'])) {
$promote_id = I('promote_id',0);
$promoteaccount = get_promote_name($promote_id);
} else {
$promoteaccount = '全部';
}
$list = D('user')->user1(strtotime($start),strtotime($end),$promote_id,$game_id);
$count = count($list);
$data = array_slice($list,($page-1)*$row,$row,true);
file_put_contents(RUNTIME_PATH.'/access_data_user.txt',json_encode($list));
if($count > $row){
$page = new \Think\Page($count, $row);
$page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
$this->assign('_page', $page->show());
}
$this->meta_title = '用户统计';
$this->assign('data',$data);
$this->assign('game_source',$gamesource);
$this->assign('promote_account',$promoteaccount);
$this->display();
}
public function multisort($records, $column, $type = 'asc')
{
$length = count($records);
for ($i = 0; $i < $length; $i ++) {
for ($j = $i + 1; $j < $length; $j ++) {
if ($type == 'asc') {
if ($records[$i][$column] > $records[$j][$column]) {
$temp = $records[$i];
$records[$i] = $records[$j];
$records[$j] = $temp;
}
} else if ($type == 'desc') {
if ($records[$i][$column] < $records[$j][$column]) {
$temp = $records[$i];
$records[$i] = $records[$j];
$records[$j] = $temp;
}
}
}
}
return $records;
}
public function userretention()
{
$this->meta_title = '留存统计';
$start = I('start', date('Y-m-d',strtotime('-7 day')));
$end = empty(I('end')) ? time_format(time(),'Y-m-d') : I('end');
$dataOrder = I('data_order', '');
$baseGameId = I('game_id', 0);
$deviceType = I('device_type', '');
$promoteId = I('promote_id', 0);
$companyId = I('company_id', 0);
$orderType = 'asc';
$orderColumn = 'date';
if ($dataOrder != '')
{
$dataOrder = explode(',', $dataOrder);
$orderType = $dataOrder[1];
$orderColumn = $dataOrder[0];
}
$status = true;
$data = false;
$error = '';
if ($baseGameId == 0) {
$error = '请选择游戏!';
$status = false;
}
$startTime = strtotime($start . ' 00:00:00');
$endTime = strtotime($end . ' 23:59:59') + 1;
if ((($endTime - $startTime)/(24*3600)) > 31) {
$error = '时间间隔不能超过31天';
$status = false;
}
$searchGameId = 0;
if ($status) {
$baseGame = M('base_game', 'tab_')->where(['id' => $baseGameId])->find();
$gameIds = [];
if ($deviceType) {
$searchGameId = $deviceType == 'android' ? $baseGame['android_game_id'] : $baseGame['ios_game_id'];
$gameIds[] = $searchGameId;
} else {
$gameIds = [$baseGame['android_game_id'], $baseGame['ios_game_id']];
}
$client = new Client([
'base_uri' => C('TASK_URL'),
'timeout' => 10.0,
]);
$response = $client->post('/statistics/player-retention', [
'verify' => false,
'form_params' => [
'start_time' => $start,
'end_time' => $end,
'promote_id' => I('promote_id', 0),
'company_id' => I('company_id', 0),
'game_ids' => $gameIds,
]
]);
$result = (string)$response->getBody();
$result = json_decode($result, true);
if (!$result) {
$this->assign('error', '数据请求异常!');
}
$data = $result['data']['records'];
$dayList = [1, 2, 3, 4, 5, 6, 7, 15, 30];
$gameName = $deviceType ? get_game_name($searchGameId) : $baseGame['name'];
$promoteName = '全部';
$promote = null;
if ($promoteId) {
$promote = M('promote', 'tab_')->where(['id' => $promoteId])->find();
$promoteName = $promote['account'];
$promote['model_type'] = 'promote';
} elseif ($companyId) {
$promote = M('promote_company', 'tab_')->where(['id' => $companyId])->find();
$promoteName = $promote['company_name'];
$promote['model_type'] = 'company';
}
foreach ($data as $key => $item) {
$item['promote_name'] = $promoteName;
$item['game_name'] = $gameName;
foreach ($dayList as $day) {
if ($item['register_count'] > 0) {
$item['retention_day'. $day] = round($item['retention_day'. $day]/$item['register_count'], 4)*100;
} else {
$item['retention_day'. $day] = '--';
}
}
$data[$key] = $item;
}
$repository = new UserRepository();
$deviceKey = 0;
if ($deviceType) {
$deviceKey = $deviceType == 'android' ? 1 : 2;
}
$otherResult = $repository->getUserRetention($baseGameId, [$start, $end], $deviceKey, $promote, [60, 90]);
foreach ($data as $key => $item) {
$otherItem = $otherResult[$item['date']];
$data[$key]['retention_day60'] = $otherItem['retention_rate'][60];
$data[$key]['retention_day90'] = $otherItem['retention_rate'][90];
}
if ($dataOrder) {
$data = $this->multisort($data, $orderColumn, $orderType);
}
} else {
$this->assign('error', $error);
}
$baseGames = M('base_game', 'tab_')->select();
$companies = M('promote_company', 'tab_')->field(['id', 'company_name'])->select();
$promoteMap = ['_string' => '1=1'];
if ($companyId) {
$promoteMap['company_id'] = $companyId;
}
$promotes = M('promote', 'tab_')->field(['id', 'account'])->where($promoteMap)->select();
$this->assign('promoteName', $promoteName);
$this->assign('promotes', $promotes);
$this->assign('companies', $companies);
$this->assign('baseGames', $baseGames);
$this->checkListOrCountAuthRestMap($map,[]);
$this->assign('showPromote', session('user_auth')['show_promote']);
$this->assign('data', $data);
$this->assign('order_type', $orderType);
$this->assign('order_column', $orderColumn);
$this->assign('data', $data);
$this->meta_title = '留存统计';
$this->display();
}
/**
* 留存统计
* @param int $p
* 06.12.3
* xmy
*/
public function playerRetention($p = 0)
{
echo "暂不开放";
die();
$request=$_REQUEST;
$page = intval($p);
$page = $page ? $page : 1; //默认显示第一页数据
$arraypage=$page;
if(isset($_REQUEST['row'])) {$row = $_REQUEST['row'];}else{$row = 10;}
$start = I('start',date('Y-m-d',strtotime('-7 day')));
$end = empty(I('end')) ? time_format(time(),'Y-m-d') : I('end');
if(!empty($start)){
$game_id = I('game_id');
$promote_id = I('promote_id');
$map_list = array();
if(I('game_id') !=0){
$map['ur.game_id']=$map_list['tab_user.fgame_id'] = $game_id;
$this->assign('game_name',get_game_name(I('game_id')));
}
if(I('promote_id') !=0){
$map['tab_user.promote_id']=$map_list['tab_user.promote_id']=$promote_id;
$this->assign('promote_name',get_promote_account(I('promote_id')));
}
//统计每日注册数
$data = $this->count_register($start,$end,$game_id,$promote_id,$page);
$day = array(1,2,3,4,5,6,7,15,30,60);
foreach ($data as $k=>$v) {
//当日注册人帐号
$time = $v['time'];
//$map["FROM_UNIXTIME(register_time,'%Y-%m-%d')"] = $time;
//每日留存
if(intval($v['register_num'])==0) {$data[$k][$value]=0;continue;}
$map['tab_user.id'] = array('in',explode(',',$v['register']));
foreach ($day as $key => $value) {
$map["register_time"] = array('between',array(strtotime($time),strtotime($time)+24*60*60-1));
$login_time = strtotime("+{$value} day",strtotime($time));
$login_time_end = $login_time+86399;
$num = M('user','tab_')
->field('count(DISTINCT tab_user.id) as num')
->join("right join tab_user_login_record as ur on ur.user_id = tab_user.id and ur.login_time between $login_time and $login_time_end")
->where($map)
->find();
$data[$k][$value] = $num['num'];
}
}
//分页
$time_map['time'] = array('between',array($start,$end));
$count = M('date_list')->where($time_map)->count();
$page = set_pagination($count,$row);
if($page) {$this->assign('_page', $page);}
}else{
unset($_REQUEST['data_order']);
if(count(I('get.'))!=0){
$this->error('时间选择错误,请重新选择!');
}
}
if($request['data_order']!=''){
$data_order=reset(explode(',',$request['data_order']));
$data_order_type=end(explode(',',$request['data_order']));
$this->assign('userarpu_order',$data_order);
$this->assign('userarpu_order_type',$data_order_type);
}
$data=my_sort($data,$data_order_type,(int)$data_order,SORT_STRING);
$size=$row;//每页显示的记录数
$pnum = ceil(count($data) / $size); //总页数ceil()函数用于求大于数字的最小整数
//用array_slice(array,offset,length) 函数在数组中根据条件取出一段值;array(数组),offset(元素的开始位置),length(组的长度)
$data = array_slice($data, ($arraypage-1)*$size, $size);
$this->assign('data',$data);
$this->meta_title = '留存统计';
$this->display();
}
/**
* 流失分析
*/
public function userloss(){
$start=get_lastweek_name(6);
$end=date('Y-m-d');
$this->assign('start',$start);
$this->assign('end',$end);
$result=$this->loss_pic($_REQUEST);
foreach ($result['day'] as $key => $value) {
$res['lossplayer']['loss'][$value]=$result['loss_count'][$key];
$res['lossplayer']['lossrate'][$value]=$result['loss_rate'][$key];
}
$money_arr=array(
">$2000","$1000~2000","$600~1000","$200~600","$100~200","$40~100","$20~40","$10~20","$2~$10","<$2",
);
foreach ($money_arr as $key => $value) {
$res['lossmoney'][$value]=$result['loss_money'][$key];
}
$times_arr=array(
">50次","41~50次","31~40次","21~30次","11~20次","6~10次","5次","4次","3次","2次","1次","未付费",
);
foreach ($times_arr as $key => $value) {
$res['losstimes'][$value]=$result['loss_times'][$key];
}
$this->meta_title = '流失分析';
$this->assign("json_data",json_encode($res));
$this->display();
}
//流失率分析
public function loss_pic($para){
if (!empty($para['time_start']) && !empty($para['time_end'])) {
$days = prDates($para['time_start'],$para['time_end']);
$day = $days;
$this->assign('tt',array_chunk($days,1));
} else {
$defTimeE = date("Y-m-d",time());
$defTimeS = date("Y-m-d",time() - 24*60*60*6);
$day = every_day(7);
$days = prDates($defTimeS,$defTimeE);
}
if (isset($para['game_id'])) {
$map['r.fgame_id']=$para['game_id'];
$map1['r.fgame_id']=$para['game_id'];
}
if (!empty($para['channel_id'])) {
if ($para['channel_id'] == 2 ) {
$continueDay = 7;
} else {
$continueDay = 3;
}
}else{
$continueDay = 3;//3天不登录表示玩家已流失
}
$usermodel = D('User');
//获取这个时间段内注册的玩家
$start = $this->get_time(current($days), $continueDay);
$end = $this->get_time(end($days), $continueDay) + 86399;;
$map['register_time']=array('between',array($start, $end));
if (isset($para['promote_id']) && $para['promote_id']!="") {
$map['promote_id']=$para['promote_id'];
}
$players = $usermodel->getUserList($map, "GROUP_CONCAT(DISTINCT id) as user_ids,
FROM_UNIXTIME(register_time+{$continueDay}*86400, '%Y-%m-%d') as register_date", "register_date");
$players = array_column($players, 'user_ids', 'register_date');
$map1 = array();
$map1['lpuid'] = 0;
$map1['u.register_time'] = array('between',array($start, $end));
if (isset($para['promote_id'])&&$para['promote_id']!="") {
$map1['u.promote_id']=$para['promote_id'];
}
//获取这段时间内有登录(未流失)的玩家
$map1['r.login_time'] = array('exp', 'BETWEEN UNIX_TIMESTAMP(
FROM_UNIXTIME(
u.register_time + 86400,
"%Y-%m-%d"
)
)
AND UNIX_TIMESTAMP(
FROM_UNIXTIME(
u.register_time + 86400,
"%Y-%m-%d"
)
) + 86400 * ' . $continueDay);
$keepPlayers = $usermodel->getKeepPlayers($map1, $continueDay, count($days) > 7);// 3或7天内有登录的玩家
$keepPlayers = array_column($keepPlayers, 'user_ids', 'register_date');
$loss_count = array();//流失玩家数量
foreach ($days as $key => $date) {
$dateUserCount = isset($players[$date]) ? count(explode(",", $players[$date])) : 0;
$keepUserCount = isset($keepPlayers[$date]) ? count(explode(",", $keepPlayers[$date])) : 0;
$loss_count[$key] = $dateUserCount - $keepUserCount;//流失数量
if ($dateUserCount) {
$loss_rate[] = sprintf("%.2f",($loss_count[$key]/$dateUserCount) * 100);//流失率
} else {
$loss_rate[] = 0;
}
}
$losers = array_filter($players, function ($item) use ($keepPlayers) {
return !in_array($item, $keepPlayers);
});
$losers = array_values($losers);//流失玩家id集合
$data2 = $this->loss_pic2($losers);
$data3 = $this->loss_pic3($losers);
$result['day'] = $day;//日期
$result['loss_count'] = $loss_count;//流失数量
$result['loss_rate'] = $loss_rate;//流失率
$result['loss_money'] = $data2;//流失金额
$result['loss_times'] = $data3;//流失次数
return $result;
}
/**
* 流失用户消费金额分析,包括不同等级的人数和所占比例
* @param [type] $data [description]
* @return [type] [description]
*/
function loss_pic2($data){
$Spend=new SpendModel();
foreach ($data as $key => $value) {
$list[$key]['user_id']=$value;
$list[$key]['amount']=$Spend->totalSpend($list[$key]);
}
foreach ($list as $k => $v) {
if($v['amount']<2){
$two[]=$v;
}elseif($v['amount']<10){
$ten[]=$v;
}elseif($v['amount']<20){
$twenty[]=$v;
}elseif($v['amount']<40){
$forty[]=$v;
}elseif($v['amount']<100){
$hundred[]=$v;
}elseif($v['amount']<200){
$thundred[]=$v;
}elseif($v['amount']<600){
$shundred[]=$v;
}elseif($v['amount']<1000){
$thousand[]=$v;
}elseif($v['amount']<2000){
$tthousand[]=$v;
}else{
$thousands[]=$v;
}
}
$result=[count($thousands),count($tthousand),count($thousand),count($shundred),count($thundred),count($hundred),count($forty),count($twenty),count($ten),count($two)];
return $result;
}
/**
* 流失用户消费次数分析,包括不同次数所占人数和比例
* @param [type] $data [description]
* @return [type] [description]
*/
public function loss_pic3($data){
$Spend=new SpendModel();
foreach ($data as $key => $value) {
$list[$key]['user_id']=$value;
$list[$key]['count']=$Spend->totalSpendTimes($list[$key]);
}
foreach ($list as $k => $v) {
if($v['count']==0){
$zero[]=$v;
}elseif($v['count']==1){
$one[]=$v;
}elseif($v['count']==2){
$two[]=$v;
}elseif($v['count']==3){
$three[]=$v;
}elseif($v['count']==4){
$four[]=$v;
}elseif($v['count']==5){
$five[]=$v;
}elseif($v['count']<11){
$ten[]=$v;
}elseif($v['count']<21){
$twenty[]=$v;
}elseif($v['count']<31){
$thirty[]=$v;
}elseif($v['count']<41){
$forty[]=$v;
}elseif($v['count']<51){
$fifty[]=$v;
}else{
$fiftys[]=$v;
}
}
$result=[count($fiftys),count($fifty),count($forty),count($thirty),count($twenty),count($ten),count($five),count($four),count($three),count($two),count($one),count($zero)];
return $result;
}
/**
* 统计注册数
* @param $start 开始时间
* @param $end 结束时间
* @param string $game_name 游戏名称
* @param string $promote_id 渠道ID
* @param int $page
*/
public function count_register($start,$end,$game_id="",$promote_id="",$page=0,$row=10){
$map["register_time"] = array('between',array(strtotime($start),strtotime($end)+86399));
$maps["time"] = array('between',array($start,$end));
if($game_id != ''){
$map['fgame_id'] = $game_id;
}
if($promote_id != ''){
$map['promote_id'] = $promote_id;
}
$map['puid']=0;
$user = M('user','tab_')->field("FROM_UNIXTIME(register_time, '%Y-%m-%d') as time,COUNT(id) AS register_num,GROUP_CONCAT(id) as register")
->where($map)
->group("time")
->select();
$user2 = array_combine(array_column($user,'time'),array_column($user,'register'));
$user = array_combine(array_column($user,'time'),array_column($user,'register_num'));
//file_put_contents(dirname(__FILE__) . '/usersql2.txt',json_encode(M('user','tab_')->getLastSql()));
//统计每日注册数
$data = M('date_list')
->field("time")
->where($maps)
->select();
foreach ($data as &$val){
$val['register_num'] = $user[$val['time']]?$user[$val['time']]:0;
$val['register'] = $user2[$val['time']]?$user2[$val['time']]:'';
}
return $data;
}
/**
* [get_time 通过日期获得时间戳]
* @param [type] $date [description]
* @return [type] [int]
*/
private function get_time($date,$d){
$date= explode("-",$date);
$year=$date[0];
$month=$date[1];
$day=$date[2];
$start=mktime(0,0,0,$month,$day,$year)-$d*24*60*60;
return $start;
}
/*
* 根据时间计算注册人数
*/
public function getcount($day, $n = null)
{
if (null !== $n) {
$map['register_time'] = get_start_end_time($day, $n);
} else {
$map = get_last_day_time($day, "register_time");
}
if (isset($_REQUEST['promote_name'])) {
if ($_REQUEST['promote_name'] == '全部') {
unset($_REQUEST['promote_name']);
} else if ($_REQUEST['promote_name'] == '自然注册') {
$map['tab_user.promote_id'] = array("elt", 0);
} else {
$map['tab_user.promote_id'] = get_promote_id($_REQUEST['promote_name']);
}
}
if (isset($_REQUEST['game_name'])) {
if ($_REQUEST['game_name'] == '全部') {
unset($_REQUEST['game_name']);
} else {
$map['tab_user.fgame_id'] = get_game_id($_REQUEST['game_name']);
}
$r_user_id = D('User')
->where($map)
->select();
for ($i = 0; $i < count($r_user_id); $i++) {
$sd[] = $r_user_id[$i]['user_id'];
}
$pid = implode(",", $sd);
$count = D("User")
->where($map)
->count();
} else {
$r_user_id = D("User")->where($map)->select();
for ($i = 0; $i < count($r_user_id); $i++) {
$sd[] = $r_user_id[$i]['id'];
}
$pid = implode(",", $sd);
$count = D("User")->where($map)->count();
}
$r_count = array($pid, $count);
return $r_count;
}
/*
* 计算留存率
*
*/
public function onelogincount($day, $count, $n = null)
{
if (null !== $n) {
$onetime['login_time'] = get_start_end_time($day, $n);
} else {
$onetime = get_last_day_time($day, "login_time");
}
if (isset($_REQUEST['promote_name'])) {
if ($_REQUEST['promote_name'] == '全部') {
unset($_REQUEST['promote_name']);
} else if ($_REQUEST['promote_name'] == '自然注册') {
$onetime['promote_id'] = array("elt", 0);
} else {
$onetime['promote_id'] = get_promote_id($_REQUEST['promote_name']);
}
} else {
$onetime['promote_id'] = array('egt', 0);
}
if (isset($_REQUEST['game_name'])) {
if ($_REQUEST['game_name'] == '全部') {
unset($_REQUEST['game_name']);
} else {
$onetime['game_id'] = get_game_id($_REQUEST['game_name']);
}
} else {
$onetime['game_id'] = array('gt', 0);
}
$onetime['user_id'] = array('in', (string)$count[0]);
$onelogincount = M("user_login_record", "tab_")->where($onetime)->count('distinct user_id');
if ($onelogincount != 0) {
if ($count[1] == 0) {
$baifen = "";
} else {
$lu = $onelogincount / $count[1];
$baifen = $lu * 100;
$baifen = $baifen > 100 ? '100%' : $baifen . '%';
}
} else {
if ($count[1] == 0) {
$baifen = "";
} elseif ($count[1] != 0) {
$baifen = "0%";
}
}
return round($baifen) . '%';
}
public function userarpu($p=0)
{
$start = I('start', date('Y-m-d'));
$end = I('end', date('Y-m-d'));
$baseGameIds = I('game_ids', '');
$promoteId = I('promote_id', 0);
$companyId = I('company_id', 0);
$dataOrder = I('data_order', '');
$deviceType = I('device_type', '');
$containBindCoins = I('contain_bind_coins', 0);
$orderType = '';
$order = 0;
if ($dataOrder != '') {
$dataOrderRow = explode(',', $dataOrder);
$order = $dataOrderRow[0];
$orderType = $dataOrderRow[1];
}
$promoteIds = [];
if ($promoteId > 0) {
$promote = M('promote', 'tab_')->field(['id', 'chain'])->where(['id' => $promoteId])->find();
$promoteIds = M('promote', 'tab_')->where(['chain' => ['like', $promote['chain'] . $promote['id'] . '/%']])->getField('id', true);
$promoteIds[] = $promote['id'];
} elseif ($companyId > 0) {
$promoteIds = M('promote', 'tab_')->where(['company_id' => $companyId])->getField('id', true);
}
$startTime = strtotime($start . ' 00:00:00');
$endTime = strtotime($end . ' 23:59:59');
$baseGameIdRows = $baseGameIds ? explode(',', $baseGameIds) : [];
$baseGames = M('base_game', 'tab_')->select();
$gameIds = null;
$conditions = [];
if (count($baseGameIdRows)) {
$tmpBaseGames = M('base_game', 'tab_')->where(['id' => ['in', $baseGameIdRows]])->select();
$gameIds = array_merge(array_column($tmpBaseGames, 'android_game_id'), array_column($tmpBaseGames, 'ios_game_id'));
}
if (count($promoteIds)) {
$conditions['promote_id'] = ['in', $promoteIds];
}
if ($deviceType != '') {
if ($gameIds) {
$gameIds = (
$deviceType == 'android' ?
array_intersect($gameIds, array_column($baseGames, 'android_game_id')) :
array_intersect($gameIds, array_column($baseGames, 'ios_game_id'))
);
} else {
$gameIds = (
$deviceType == 'android' ?
array_column($baseGames, 'android_game_id') :
array_column($baseGames, 'ios_game_id')
);
}
}
if ($gameIds && count($gameIds)) {
if (count($gameIds)) {
$conditions['game_id'] = ['in', $gameIds];
} else {
$conditions['game_id'] = ['in', 0];
}
}
// 新增用户
/* M('user', 'tab_')
->field('count(*) count, FROM_UNIXTIME(register_time, "%Y-%m-%d") date')
->where([
'game_id' => ['in', $gameIdRows],
'register_time' => ['between', [$startTime, $endTime]]
])
->group('date')
->select(); */
$newUsers = M('user_play', 'tab_')
->field('count(DISTINCT user_id) count, FROM_UNIXTIME(create_time, "%Y-%m-%d") date')
->where(array_merge($conditions, ['create_time' => ['between', [$startTime, $endTime]]]))
->group('date')
->select();
$newUsers = index_by_column('date', $newUsers);
// 活跃用户
$loginUsers = M('login_daily_record', 'tab_')
->field('count(DISTINCT user_id) count, FROM_UNIXTIME(create_time, "%Y-%m-%d") date')
->where(array_merge($conditions, ['create_time' => ['between', [$startTime, $endTime]]]))
->group('date')
->select();
$loginUsers = index_by_column('date', $loginUsers);
$spendConditions = array_merge($conditions, [
'pay_time' => ['between', [$startTime, $endTime]],
'pay_status' => 1,
]);
if ($containBindCoins == 0) {
$spendConditions['pay_way'] = ['gt', -1];
}
// 付费玩家,付费金额
$payLogs = M('spend', 'tab_')
->field('count(DISTINCT user_id) count, sum(pay_amount) amount, FROM_UNIXTIME(pay_time, "%Y-%m-%d") date')
->where($spendConditions)
->group('date')
->select();
$payLogs = index_by_column('date', $payLogs);
$rows = [];
for ($time = $startTime; $time < $endTime; $time = $time + 24*3600) {
$date = date('Y-m-d', $time);
$newUser = isset($newUsers[$date]) ? $newUsers[$date]['count'] : 0;
$loginUser = isset($loginUsers[$date]) ? $loginUsers[$date]['count'] : 0;
$payAmount = isset($payLogs[$date]) ? $payLogs[$date]['amount'] : 0;
$payUser = isset($payLogs[$date]) ? $payLogs[$date]['count'] : 0;
$rows[] = [
'date' => $date,
'new_user' => $newUser,
'login_user' => $loginUser,
'pay_amount' => $payAmount,
'pay_user' => $payUser,
'pay_rate' => $loginUser > 0 ? (round($payUser / $loginUser * 100, 2)) : '0',
'arpu' => $loginUser > 0 ? (round($payAmount / $loginUser, 2)) : '0.00',
'arppu' => $payUser > 0 ? (round($payAmount / $payUser, 2)) : '0.00',
];
}
if (I('export', 0) == 1) {
$fields = [
'date' => '日期',
'new_user' => '新增玩家',
'login_user' => '活跃玩家',
'pay_amount' => '充值金额',
'pay_user' => '付费玩家',
'pay_rate' => '付费率',
'arpu' => 'ARPU',
'arppu' => 'ARPPU',
];
foreach ($rows as &$item) {
$item['pay_rate'] = $item['pay_rate'] . '%';
}
addOperationLog(['op_type'=>3,'key'=>getNowDate(),'op_name'=>'ARPU分析','url'=>U('Stat/userarpu'),'menu'=>'统计-数据分析-ARPU分析']);
data2csv($rows, '数据分析_ARPU分析', $fields);
exit;
}
if ($dataOrder) {
$sort = $order == 3 ? SORT_DESC : SORT_ASC;
$orderColumn = array_column($rows, $orderType);
array_multisort($orderColumn, $sort, SORT_REGULAR, $rows);
}
$this->checkListOrCountAuthRestMap($map,[]);
$this->meta_title = 'ARPU统计';
$companies = M('promote_company', 'tab_')->field(['id', 'company_name'])->select();
$promoteMap = ['_string' => '1=1'];
if ($companyId) {
$promoteMap['company_id'] = $companyId;
}
$promotes = M('promote', 'tab_')->field(['id', 'account'])->where($promoteMap)->select();
$this->assign('promotes', $promotes);
$this->assign('companies', $companies);
$this->assign('showPromote', session('user_auth')['show_promote']);
$this->assign('baseGames', $baseGames);
$this->assign('records', $rows);
$this->assign('order', $order);
$this->assign('orderType', $orderType);
$this->display();
}
public function userarpu_old($p=0)
{
$request=$_REQUEST;
$page = intval($p);
$page = $page ? $page : 1; //默认显示第一页数据arraypage
$arraypage = $page ? $page : 1; //默认显示第一页数据
if(isset($_REQUEST['row'])) {$row = $_REQUEST['row'];}else{$row = 10;}
$start = I('start');
$end = empty(I('end')) ? time_format(time(),'Y-m-d') : I('end');
$game_id = I('game_id');
$promote_id = I('promote_id');
$map_list = array();
if ($_REQUEST['hasbindcoins'] == 1) {
unset($hasbindcoins['pay_way']);
} else {
$hasbindcoins['pay_way'] = array('gt',-1);
}
if(I('game_id') !=0){
$this->assign('game_name',get_game_name(I('game_id')));
}
if(I('promote_id') !=0){
$this->assign('promote_name',get_promote_account(I('promote_id')));
}
if(I('game_id') != '') $map_list['game_id'] = I('game_id');
if(I('promote_id') != '') $map_list['promote_id'] = I('promote_id');
if(!empty($start)) {
//新增玩家
// $data = $this->count_register($start, $end, $game_id, $promote_id, $page);
$data = $this->count_register($start, $end, $game_id, $promote_id);
// var_dump($data);exit;
foreach ($data as $key => $value) {
$time = $value['time'];
//活跃玩家
$data[$key]['act_user'] = $this->count_act_user($time,$game_id,$promote_id);
//1日留存
$map = $map_list;
if($map_list['promote_id']!=''){
$map['tab_user.promote_id']=$map_list['promote_id'];
}
unset($map['promote_id']);
//$map["FROM_UNIXTIME(,'%Y-%m-%d')"] = $time;
$map["register_time"] = ['between', [strtotime($time), strtotime($time)+86399]];
$login_time = strtotime("+1 day",strtotime($time));
$login_time_end = $login_time+86399;
$num_sql = M('user','tab_')
->field('tab_user.id')
->join("right join tab_user_login_record as ur on ur.user_id = tab_user.id
and ur.login_time between $login_time and $login_time_end")
->where($map)
->group('user_id')
->find();
if (!empty($data[$key]['register_num'])) {
$data[$key]['keep_num'] = round($num['num']/$data[$key]['register_num'],4)*100;
} else {
$data[$key]['keep_num'] = 0;
}
//充值
$map = $map_list;
empty($game_name ) || $map['game_name'] = array('like','%'.$game_name.'%');
empty($promote_id) || $map['promote_id'] = $promote_id;
$map['pay_status'] = 1;
$map["pay_time"] = ['between',[strtotime($time),strtotime($time)+86399]];
empty($hasbindcoins) || $map['pay_way'] = $hasbindcoins['pay_way'];
$spend = M('spend','tab_')->field("IFNULL(sum(pay_amount),0) as money,IFNULL(count(distinct user_id),0) as people")
->where($map)->find();
$data[$key]['spend'] = $spend['money'];
//付费玩家数
$data[$key]['spend_people'] = $spend['people'];
//新付费玩家
$newmap = $map_list;
empty($hasbindcoins) || $newmap['pay_way'] = $hasbindcoins['pay_way'];
$newmap['pay_status'] = 1;
$sql = M('spend','tab_')
->field("user_id,min(pay_time) as time")
->group('user_id')
->where(array_merge($newmap,['_string'=>'(small_id=0 or small_id=user_id)']))
->select(false);
//$sql = "select IFNULL(count(user_id),0) as num from ({$sql}) as t WHERE FROM_UNIXTIME(t.time,'%Y-%m-%d') = '{$time}'";
$sql = M('spend','tab_')
->table('('.$sql.') as t')
->field('IFNULL(count(user_id),0) as num')
->where(array('time'=>['between',[strtotime($time),strtotime($time)+86399]]))
->select(false);
$query = M()->query($sql);
$data[$key]['new_pop'] = $query[0]['num'];
//付费率
if (!empty($data[$key]['act_user'])) {
$data[$key]['spend_rate'] = round($data[$key]['spend_people']/$data[$key]['act_user'],4)*100;
} else {
$data[$key]['spend_rate'] = 0;
}
//ARPU
if (!empty($data[$key]['act_user'])) {
$data[$key]['ARPU'] = round($data[$key]['spend']/$data[$key]['act_user'],2);
} else {
$data[$key]['ARPU'] = 0;
}
//ARPPU
if (!empty($data[$key]['spend_people'])) {
$data[$key]['ARPPU'] = round($data[$key]['spend']/$data[$key]['spend_people'],2);
} else {
$data[$key]['ARPPU'] = 0;
}
//累计付费玩家
$map = $map_list;
empty($hasbindcoins) || $map['pay_way'] = $hasbindcoins['pay_way'];
$map['pay_status'] = 1;
$map["pay_time"] = array('elt',strtotime($time)+86399);
$pop_num = M('spend','tab_')->field('count(distinct user_id) as num')->where($map)->select();
$data[$key]['pop_num'] = $pop_num[0]['num'];
}
//分页
$time_map['time'] = array('between',array($start,$end));
$count = M('date_list')->where($time_map)->count();
$page = set_pagination($count,$row);
if($page) {$this->assign('_page', $page);}
}else{
unset($_REQUEST['data_order']);
if(count(I('get.'))!=0){
$this->error('时间选择错误,请重新选择!');
}
}
if($request['data_order']!=''){
$data_order=reset(explode(',',$request['data_order']));
$data_order_type=end(explode(',',$request['data_order']));
$this->assign('userarpu_order',$data_order);
$this->assign('userarpu_order_type',$data_order_type);
}
$this->checkListOrCountAuthRestMap($map,[]);
$data=my_sort($data,$data_order_type,(int)$data_order,SORT_STRING);
$size=$row;//每页显示的记录数
$pnum = ceil(count($data) / $size); //总页数ceil()函数用于求大于数字的最小整数
//用array_slice(array,offset,length) 函数在数组中根据条件取出一段值;array(数组),offset(元素的开始位置),length(组的长度)
$data = array_slice($data, ($arraypage-1)*$size, $size);
$this->meta_title = 'ARPU统计';
$this->assign('data',$data);
$this->display();
}
/**
* 获取活跃用户数
* @param $time
*/
public function count_act_user($time,$game_id="",$promote_id=""){
$map["login_time"] = ['between',[strtotime($time),strtotime($time)+86399]];
$map1["register_time"]=['between',[strtotime($time),strtotime($time)+86399]];
empty($game_id) || $map['game_id'] = $game_id;
empty($game_id) || $map1['fgame_id'] = $game_id;
if(!empty($promote_id)){
$user=M('User','tab_')->field('id')->where(array('promote_id'=>$promote_id))->select();
$user=implode(',',array_column($user,'id'));
$map['user_id']=array('in',$user);
$map1['id']=array('in',$user);
};
$uudata=M('User','tab_')
->field('id as user_id')
->where($map1)
->select(false);
$data = M('user_login_record','tab_')
->field('user_id')
->where($map)
->union($uudata)
->group('user_id')
->select();
$data=count($data);
return $data;
}
//计算指定日期新用户数
public function getnewcount($time)
{
$map = array();
if (!empty($time)) {
$map['register_time'] = get_start_end_time($_REQUEST['time-start']);
} else {
$map['register_time'] = -1;
}
if (isset($_REQUEST['promote_name'])) {
if ($_REQUEST['promote_name'] == '全部') {
unset($_REQUEST['promote_name']);
} else if ($_REQUEST['promote_name'] == '自然注册') {
$map['promote_id'] = array("elt", 0);
} else {
$map['promote_id'] = get_promote_id($_REQUEST['promote_name']);
}
} else {
$map['promote_id'] = array('egt', 0);
}
if (isset($_REQUEST['game_name'])) {
if ($_REQUEST['game_name'] == '全部') {
unset($_REQUEST['game_name']);
} else {
$map['fgame_id'] = get_game_id($_REQUEST['game_name']);
}
} else {
$map['fgame_id'] = array('gt', 0);
}
$r_user_id = M("User", "tab_")
->where($map)
->select();
for ($i = 0; $i < count($r_user_id); $i++) {
$sd[] = $r_user_id[$i]['id'];
}
$pid = implode(",", $sd);
$count = M("User", "tab_")
->where($map)
->count();
$count = array($pid, $count);
return $count;
}
//计算留存数
public function getplaycount($day, $count, $n = null)
{
if (null !== $n) {
$onetime['login_time'] = get_start_end_time($day, $n);
} else {
$onetime = get_last_day_time($day, "login_time");
}
if (isset($_REQUEST['promote_name'])) {
if ($_REQUEST['promote_name'] == '全部') {
unset($_REQUEST['promote_name']);
} else if ($_REQUEST['promote_name'] == '自然注册') {
$onetime['promote_id'] = array("elt", 0);
} else {
$onetime['promote_id'] = get_promote_id($_REQUEST['promote_name']);
}
} else {
$onetime['promote_id'] = array('egt', 0);
}
if (isset($_REQUEST['game_name'])) {
if ($_REQUEST['game_name'] == '全部') {
unset($_REQUEST['game_name']);
} else {
$onetime['game_id'] = get_game_id($_REQUEST['game_name']);
}
} else {
$onetime['game_id'] = array('gt', 0);
}
$onetime['user_id'] = array('in', (string)$count[0]);
$onelogincount = M("user_login_record", "tab_")->where($onetime)->count('distinct user_id');
return $onelogincount;
}
//计算次日留存率
function get_cilogin($newcount, $cicount)
{
if ($cicount == 0) {
return sprintf("%.2f", 0) . '%';
} else {
return round($cicount / $newcount * 100) . '%';
}
}
//计算指定游戏 用户总数 与时间无关
public function getallcount()
{
$map = array();
if (!isset($_REQUEST['time-start'])) {
$map['a.register_time'] = -1;
}
if (isset($_REQUEST['game_name'])) {
if ($_REQUEST['game_name'] == '全部') {
unset($_REQUEST['game_name']);
} else {
$map['a.fgame_id'] = get_game_id($_REQUEST['game_name']);
}
} else {
$map['a.fgame_id'] = array('gt', 0);
}
if (isset($_REQUEST['promote_name'])) {
if ($_REQUEST['promote_name'] == '全部') {
unset($_REQUEST['promote_name']);
} else if ($_REQUEST['promote_name'] == '自然注册') {
$map['a.promote_id'] = array("elt", 0);
} else {
$map['a.promote_id'] = get_promote_id($_REQUEST['promote_name']);
}
} else {
$map['a.promote_id'] = array('egt', 0);
}
$count = M("User as a", "tab_")
->field("count(*) as count")
->where($map)
->count();
return $count;
}
//计算付费用户数
public function getpaycount()
{
$count = 0;
if (isset($_REQUEST['time-start'])) {
$map['pay_time'] = array("lt", strtotime($_REQUEST['time-start']) + (60 * 60 * 24));
} else {
$map['pay_time'] = -1;
}
$map['pay_status'] = 1;
if (isset($_REQUEST['game_name'])) {
if ($_REQUEST['game_name'] == '全部') {
unset($_REQUEST['game_name']);
} else {
$map['game_id'] = get_game_id($_REQUEST['game_name']);
}
} else {
$map['game_id'] = array('gt', 0);
}
if (isset($_REQUEST['promote_name'])) {
if ($_REQUEST['promote_name'] == '全部') {
unset($_REQUEST['promote_name']);
} else if ($_REQUEST['promote_name'] == '自然注册') {
$map['promote_id'] = array("elt", 0);
} else {
$map['promote_id'] = get_promote_id($_REQUEST['promote_name']);
}
} else {
$map['promote_id'] = array('egt', 0);
}
$count = M("spend", "tab_")
->where($map)
->count('distinct id');
return $count;
}
//计算新用户付费金额
public function getnewpaycount()
{
$count = 0;
if (isset($_REQUEST['time-start'])) {
$map['pay_time'] = array("lt", strtotime($_REQUEST['time-start']) + (60 * 60 * 24));
$newuser = $this->getnewcount($_REQUEST['time-start']);
$map['user_id'] = array('in', (string)$newuser[0]);
} else {
$map['pay_time'] = -1;
}
$map['pay_status'] = 1;
if (isset($_REQUEST['game_name'])) {
if ($_REQUEST['game_name'] == '全部') {
unset($_REQUEST['game_name']);
} else {
$map['a.fgame_id'] = get_game_id($_REQUEST['game_name']);
}
} else {
$map['a.fgame_id'] = array('gt', 0);
}
if (isset($_REQUEST['promote_name'])) {
if ($_REQUEST['promote_name'] == '全部') {
unset($_REQUEST['promote_name']);
} else if ($_REQUEST['promote_name'] == '自然注册') {
$map['a.promote_id'] = array("elt", 0);
} else {
$map['a.promote_id'] = get_promote_id($_REQUEST['promote_name']);
}
} else {
$map['a.promote_id'] = array('egt', 0);
}
$list = M("User as a", "tab_")
->field("sum(pay_amount) as sum")
->join("tab_spend as c on c.game_id=a.fgame_id")
->where($map)
->group('a.id')
->find();
if (!empty($list['sum'])) {
$count = $list['sum'];
}
return sprintf("%.2f", $count);
}
//计算总付费金额
public function getallpaycount()
{
$count = 0;
$map = array();
if (!isset($_REQUEST['time-start'])) {
$map['pay_time'] = -1;
}
$map['pay_status'] = 1;
if (isset($_REQUEST['game_name'])) {
if ($_REQUEST['game_name'] == '全部') {
unset($_REQUEST['game_name']);
} else {
$map['game_id'] = get_game_id($_REQUEST['game_name']);
}
} else {
$map['game_id'] = array('gt', 0);
}
if (isset($_REQUEST['promote_name'])) {
if ($_REQUEST['promote_name'] == '全部') {
unset($_REQUEST['promote_name']);
} else if ($_REQUEST['promote_name'] == '自然注册') {
$map['promote_id'] = array("elt", 0);
} else {
$map['promote_id'] = get_promote_id($_REQUEST['promote_name']);
}
} else {
$map['promote_id'] = array('egt', 0);
}
$list = M("spend", "tab_")
->field("sum(pay_amount) as sum")
->where($map)
->find();
if (!empty($list['sum'])) {
$count = $list['sum'];
}
return sprintf("%.2f", $count);
}
//计算总付费率
public function getrate()
{
$pr = $this->getpaycount();//总付费人数
$all = $this->getallcount();
if ($all == 0) {
$count = 0;
} else {
$count = $pr / $all;
$count = $count > 1 ? 100 : $count * 100;
}
return sprintf("%.2f", $count) . '%';
}
// 计算活跃用户数(当前日期所在一周的时间)
public function gethuocount()
{
$count = 0;
if (isset($_REQUEST['game_name']) || isset($_REQUEST['time-start'])) {
if (isset($_REQUEST['game_name'])) {
if ($_REQUEST['game_name'] == '全部') {
unset($_REQUEST['game_name']);
} else {
$map['game_id'] = $_REQUEST['game_id'];
$time = date("Y-m-d", time());
$start = strtotime("$time - 6 days");
//周末
$end = strtotime("$time");
$map['login_time'] = array("between", array($start, $end));
}
}
if (isset($_REQUEST['time-start'])) {
$time2 = $_REQUEST['time-start'];
$start2 = strtotime("$time2 - 6 days");
//周末
$end2 = strtotime("$time2");
$map['login_time'] = array("between", array($start2, $end2));
}
$data = M("user_login_record", "tab_")
->group('user_id')
->having('count(user_id) > 2')
->where($map)
->select();
$count = count($data);
}
return sprintf("%.2f", $count);
}
//获取用户ARPU
public function getuserarpu()
{
$new = $this->getnewpaycount();
if (isset($_REQUEST['time-start'])) {
$newcount = end($this->getnewcount($_REQUEST['time-start']));
if ($newcount == 0) {
$count = 0;
} else {
$count = $new / $newcount;
}
} else {
$count = 0;
}
return sprintf("%.2f", $count);
}
// 获取活跃ARPU
public function gethuoarpu()
{
if (isset($_REQUEST['game_name']) || isset($_REQUEST['time-start'])) {
if (isset($_REQUEST['game_name'])) {
if ($_REQUEST['game_name'] == '全部') {
unset($_REQUEST['game_name']);
} else {
$map['tab_user_login_record.game_id'] = get_game_id($_REQUEST['game_name']);
$time = date("Y-m-d", time());
$start = strtotime("$time - 6 days");
//周末
$end = strtotime("$time");
$map['login_time'] = array("between", array($start, $end));
}
}
if (isset($_REQUEST['time-start'])) {
$time2 = $_REQUEST['time-start'];
$start2 = strtotime("$time2 - 6 days");
//周末
$end2 = strtotime("$time2");
$map['login_time'] = array("between", array($start2, $end2));
}
$data = M("user_login_record", "tab_")
->group('user_id')
->having('count(user_id) > 2')
->where($map)
->select();
foreach ($data as $key => $value) {
$data1[] = $value['user_id'];
}
foreach ($data1 as $value) {
$user_account[] = get_user_account($value);
}
$pid = implode(',', $user_account);
}
$map['user_account'] = array('in', $pid);
if ($pid != '') {
$huosum = M("spend ", "tab_")
->distinct(true)
->field("pay_amount")
->join("tab_user_login_record on tab_spend.game_id = tab_user_login_record.game_id")
->where($map)
->select();
foreach ($huosum as $value) {
$huosum2[] = $value['pay_amount'];
}
$sum = array_sum($huosum2);
$count = count($data);
$return = $sum / $count;
} else {
$return = 0;
}
return $return;
}
//获取付费ARPU
public function getpayarpu()
{
$paysum = $this->getallpaycount();//所有用户付费
$paycount = $this->getpaycount();//新用户付费
if ($paycount != 0) {
$count = $paysum / $paycount;
} else {
$count = 0;
}
return sprintf("%.2f", $count);
}
public function cha_userarpu($p=0){
$page = intval($p);
$page = $page ? $page : 1; //默认显示第一页数据arraypage
$arraypage = $page ? $page : 1; //默认显示第一页数据
$row = 10;
$time = $_REQUEST['time'];
$promote_id = $_REQUEST['promote_id'];
$join = "left join tab_user u on u.fgame_id = tab_game.id";
if($time==''){
$this->error('参数错误,缺少时间');
}else{
$map['register_time']=array('between',array(strtotime($time),strtotime($time)+24*60*60-1));
}
if($promote_id!=''){
$map_list['promote_id']=$promote_id;
$map['promote_id']=$promote_id;
$join .= " AND u.promote_id = {$promote_id}";
}
if ($_REQUEST['hasbindcoins'] == 1) {
unset($hasbindcoins['pay_way']);
} else {
$hasbindcoins['pay_way'] = array('gt',-1);
}
$map['puid']=0;
$data=M('Game','tab_')->field('id as game_id, game_name')->order('id desc')->select();
foreach ($data as $key => $value) {
$game_id = $value['game_id'];
$map_list['game_id']=$game_id;
$user=M('User','tab_');
$spend=M('spend','tab_');
//新增人数
$rdata=$user
->field('count(id) as register_num')
->where(array('fgame_id'=>$game_id))
->where($map)
->find();
$data[$key]['register_num']=$rdata['register_num'];
//活跃玩家
$data[$key]['act_user'] = $this->count_act_user($time,$game_id,$promote_id);
//1日留存
$mapl=$map_list;
$mapl["register_time"] = ['between',[strtotime($time),strtotime($time)+86399]];
if ($promote_id!='')
$mapl['tab_user.promote_id']=$mapl['promote_id'];
unset($mapl['promote_id']);
$login_time = date('Y-m-d', strtotime("+1 day",strtotime($time)));
$login_start = strtotime($login_time);
$login_end = $login_start + 86399;
$num = $user
->field('count(DISTINCT tab_user.id) as num')
->join("right join tab_user_login_record as ur on ur.user_id = tab_user.id and ur.login_time between {$login_start} and {$login_end}")
->where($mapl)
->find();
if (!empty($data[$key]['register_num'])) {
$data[$key]['keep_num'] = round($num['num']/$data[$key]['register_num'],4)*100;
} else {
$data[$key]['keep_num'] = 0;
}
//充值
$mapl = $map_list;
empty($game_name ) || $mapl['game_name'] = array('like','%'.$game_name.'%');
empty($promote_id) || $mapl['promote_id'] = $promote_id;
empty($hasbindcoins) || $mapl['pay_way'] = $hasbindcoins['pay_way'];
$mapl['pay_status'] = 1;
$mapl["pay_time"] = ['between',[strtotime($time),strtotime($time)+86399]];
$spend = $spend->field("IFNULL(sum(pay_amount),0) as money,IFNULL(count(distinct user_id),0) as people")->where($mapl)->find();
$data[$key]['spend'] = $spend['money'];
//付费玩家数
$data[$key]['spend_people'] = $spend['people'];
//付费率
if (!empty($data[$key]['act_user'])) {
$data[$key]['spend_rate'] = round($data[$key]['spend_people']/$data[$key]['act_user'],4)*100;
} else {
$data[$key]['spend_rate'] = 0;
}
//ARPU
if (!empty($data[$key]['act_user'])) {
$data[$key]['ARPU'] = round($data[$key]['spend']/$data[$key]['act_user'],2);
} else {
$data[$key]['ARPU'] = 0;
}
//ARPPU
if (!empty($data[$key]['spend_people'])) {
$data[$key]['ARPPU'] = round($data[$key]['spend']/$data[$key]['spend_people'],2);
} else {
$data[$key]['ARPPU'] = 0;
}
// if($data[$key]['register_num']==0&&$data[$key]['act_user']==0&&$data[$key]['keep_num']==0&&$data[$key]['spend']==0&&$data[$key]['spend_people']==0){
// unset($data[$key]);
// }
}
$count=count($data);
if($count > $row){
$page = new \Think\Page($count, $row);
$page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
$this->assign('_page', $page->show());
}
$size=$row;//每页显示的记录数
$pnum = ceil(count($data) / $size); //总页数ceil()函数用于求大于数字的最小整数
//用array_slice(array,offset,length) 函数在数组中根据条件取出一段值;array(数组),offset(元素的开始位置),length(组的长度)
$data = array_slice($data, ($arraypage-1)*$size, $size);
$this->assign('list_data',$data);
$this->display();
}
function game_analysis(){
if($_REQUEST['time-start']!=''&&$_REQUEST['time-end']!=''){
$start=$_REQUEST['time-start'];
$end=$_REQUEST['time-end'];
}else{
$start=get_lastweek_name(6);
$end=date('Y-m-d');
}
$umap['register_time']=array('BETWEEN',array(strtotime($start),strtotime($end)+24*60*60-1));
$smap['pay_time']=array('BETWEEN',array(strtotime($start),strtotime($end)+24*60*60-1));
if($_REQUEST['promote_id']!=''){
$umap['promote_id']=$_REQUEST['promote_id'];
$smap['promote_id']=$_REQUEST['promote_id'];
}
$data=M('Game','tab_')->field('id as game_id, game_name')->order('id desc')->select();
foreach ($data as $key => $value) {
$umap['fgame_id']=$value['game_id'];
$smap['game_id']=$value['game_id'];
$udata=M('User','tab_')
->field('count(id) as register_num')
->where($umap)
->find();
$data[$key]['count']=$udata['register_num'];
$smap['pay_status']=1;
$sdata=M('Spend','tab_')
->field('ifnull(sum(pay_amount),0) as sum')
->where($smap)
->find();
$data[$key]['sum']=$sdata['sum'];
}
if($_REQUEST['data_order']==2){
$data_order_type='sum';
$data_order=3;//倒序
}else{
$data_order_type='count';
$data_order=3;
}
$data=my_sort($data,$data_order_type,(int)$data_order);
$data = array_slice($data, 0, 12);
// 前台显示
// X轴游戏
$xAxis="[";
foreach ($data as $tk => $tv) {
$xAxis.="'".$tv['game_name']."',";
}
$xAxis.="]";
//x轴注册数据
$xzdate="[";
foreach ($data as $key => $value) {
$xzdate.="'".$value['count']."',";
}
$xzdate.="]";
//x轴充值数据
$xsdate="[";
foreach ($data as $key => $value) {
$xsdate.="'".$value['sum']."',";
}
$xsdate.="]";
$this->meta_title = '游戏分析';
$this->assign('xzdate',$xzdate);
$this->assign('xsdate',$xsdate);
$this->assign('xAxis',$xAxis);
$this->assign('start',$start);
$this->assign('end',$end);
$this->assign('data',$data);
$this->display();
}
function promote_analysis(){
if($_REQUEST['time-start']!=''&&$_REQUEST['time-end']!=''){
$start=$_REQUEST['time-start'];
$end=$_REQUEST['time-end'];
}else{
$start=get_lastweek_name(6);
$end=date('Y-m-d');
}
$umap['register_time']=array('BETWEEN',array(strtotime($start),strtotime($end)+24*60*60-1));
$smap['pay_time']=array('BETWEEN',array(strtotime($start),strtotime($end)+24*60*60-1));
$hStart = strtotime($start);
$hEnd = strtotime($end)+24*60*60-1;
if($_REQUEST['game_id']!=''){
$umap['fgame_id']=$_REQUEST['game_id'];
$smap['game_id']=$_REQUEST['game_id'];
}
$data=M('Promote','tab_')->field('id as promote_id,account as promote_name')->order('id desc')->select();
foreach ($data as $key => $value) {
$umap['promote_id']=$value['promote_id'];
$smap['promote_id']=$value['promote_id'];
$echohavingUser = $havingUser.' and promote_id = '.$value['promote_id'];
$udata=M('User','tab_')
->field('count(id) as register_num,register_time,fgame_id,promote_id')
->where($umap)
->find();
$data[$key]['count']=$udata['register_num'];
$smap['pay_status']=1;
$sdata=M('Spend','tab_')
->field('ifnull(sum(pay_amount),0) as sum')
->where($smap)
->find();
$data[$key]['sum']=$sdata['sum'];
}
$data_order_type = '';
if($_REQUEST['data_order']==2){
$data_order_type='sum';
$data_order=3;//倒序
}else{
$data_order_type='count';
$data_order=3;
}
$data=my_sort($data,$data_order_type,(int)$data_order);
$data = array_slice($data, 0, 12);
// 前台显示
// X轴游戏
$xAxis="[";
foreach ($data as $tk => $tv) {
$xAxis.="'".$tv['promote_name']."',";
}
$xAxis.="]";
//x轴注册数据
$xzdate="[";
foreach ($data as $key => $value) {
$xzdate.="'".$value['count']."',";
}
$xzdate.="]";
//x轴充值数据
$xsdate="[";
foreach ($data as $key => $value) {
$xsdate.="'".$value['sum']."',";
}
$xsdate.="]";
$this->meta_title = '推广员分析';
$this->assign('xzdate',$xzdate);
$this->assign('xsdate',$xsdate);
$this->assign('xAxis',$xAxis);
$this->assign('start',$start);
$this->assign('end',$end);
$this->assign('data',$data);
$this->display();
}
/*
* 应用概况
* @author 鹿文学
*/
public function device_survey() {
set_time_limit(0);
// $device = D('DeviceRecord');
// 统计
// $total = $device->all_device();
// $todaystart = mktime(0,0,0,date('m'),date('d'),date('Y'));
// $today = $device->total_device(['create_time'=>array('between',[$todaystart,$todaystart+86399])]);
// $yesterday = $device->total_device(['create_time'=>array('between',[$todaystart-86400,$todaystart-1])]);
//
// $day7 = $device->total_device(['create_time'=>array('between',[$todaystart-86400*7,$todaystart-1])],1);
//
//
// $day30 = $device->total_device(['create_time'=>array('between',[$todaystart-86400*30,$todaystart-1])],1);
// $duration = $device->single_duration(['create_time'=>array('between',[$todaystart-86400*7,$todaystart-1])]);
// $this->assign('total',$total);
// $this->assign('today',$today);
// $this->assign('yesterday',$yesterday);
// $this->assign('day7',$day7);
// $this->assign('day30',$day30);
// $this->assign('duration7',second_to_duration($duration/7));
// 日历
R('Index/calendar');
// 折线图
$this->foldLineDiagram($_REQUEST['start'],$_REQUEST['end'],$_REQUEST['num']);
$this->checkListOrCountAuthRestMap($map,[]);
$this->display();
}
public function getDevice() {
set_time_limit(0);
$type = I("type",0);
$device = D('DeviceRecord');
$todaystart = mktime(0,0,0,date('m'),date('d'),date('Y'));
$model = M('device_statistics','tab_');
if ($type == 0) {
$return = $model->where(array('time'=>array('neq',0)))->sum('new_device');
// $return = $device->all_device();
} else if($type == 1) {
$return = $model->where(['time'=>array('between',[$todaystart,$todaystart+86399])])->sum('new_device');
// $return = $device->total_device(['create_time'=>array('between',[$todaystart,$todaystart+86399])]);
} else if($type == 2) {
$return = $model->where(['time'=>array('between',[$todaystart-86400,$todaystart-1])])->sum('new_device');
// $return = $device->total_device(['create_time'=>array('between',[$todaystart-86400,$todaystart-1])]);
} else if($type == 3) {
// $return = $model->where(['time'=>array('between',[$todaystart-86400*7,$todaystart-1])])->sum('active_device');
$return = $this->getActiveDeviceNum(['time'=>['between',[$todaystart-86400*7,$todaystart-1]]]);
// $return = $device->total_device(['create_time'=>array('between',[$todaystart-86400*7,$todaystart-1])],1);
} else if($type == 4) {
// $return = $model->where(['time'=>array('between',[$todaystart-86400*30,$todaystart-1])])->sum('active_device');
$return = $this->getActiveDeviceNum(['time'=>array('between',[$todaystart-86400*30,$todaystart-1])]);
// $return = $device->total_device(['create_time'=>array('between',[$todaystart-86400*30,$todaystart-1])],1);
} else if ($type == 5) {
$return = second_to_duration(($model->where(['time'=>$todaystart])->sum('duration7')));
// $return = second_to_duration($device->single_duration(['create_time'=>array('between',[$todaystart-86400*7,$todaystart-1])])/7);
}
$this->ajaxReturn($return?$return:0) ;
}
public function getActiveDeviceNum($map) {
$modelData = M('device_statistics','tab_')
->field("model")
->where($map)
->select();
$modelNew = 0;
$unique_code = [];
foreach($modelData as $key => $value) {
$resolveData = json_decode($value['model'],true);
// dump($resolveData);
foreach($resolveData as $k => $v) {
// if (!isset($modelNew[$v['model']][$v['version']])) {
// $modelNew = 1;
// $unique_code[$v['unique_code']] = 1;
// }
// else
if(!$unique_code[$v['unique_code']]){
$modelNew++;
$unique_code[$v['unique_code']] = 1;
// array_push($unique_code,$v['unique_code']);
}
}
}
return $modelNew;
}
/*
* 折线图
* @param integer $start 开始时间
* @param integer $end 结束时间
* @param boolean $flag 是否ajax返回
* @author 鹿文学
*/
public function foldLineDiagram($start='',$end='',$num='',$flag=false) {
$starttime = $start?strtotime($start):mktime(0,0,0,date('m'),date('d')-1,date('Y'));
$endtime = $end?strtotime($end)+86399:$starttime+86399;
$start = date('Y-m-d',$starttime);
$end = date('Y-m-d',$endtime);
$device = D('DeviceRecord');
if ($start == $end) {
$day_count = 1;
if ($start == date('Y-m-d',strtotime('-1 day'))) {$num = 2;}
$hours = ['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23'];
$data['date'] = [$start];
$data['hours'] = 1;
foreach($hours as $v) {
$data['news']['ios'][$v] = 0;
$data['news']['and'][$v] = 0;
$data['active']['ios'][$v] = 0;
$data['active']['and'][$v] = 0;
}
$deviceDataAnd = M("device_statistics","tab_")->where(['time'=>strtotime($start),'version'=>1])->find();
$deviceDataIos = M("device_statistics","tab_")->where(['time'=>strtotime($start),'version'=>2])->find();
// 新增设备
// $hoursnews = $device->news_on_time(['create_time'=>['between',[$starttime,$endtime]]],'news',5,'time,version');
$hoursnews = array_merge(json_decode($deviceDataAnd['today_new_device'],true),json_decode($deviceDataIos['today_new_device'],true));
// 活跃设备
// $hoursactive = $device->active_on_time(['create_time'=>['between',[$starttime,$endtime]]],'active',5,'time,version');
$hoursactive = array_merge(json_decode($deviceDataAnd['today_active_device'],true),json_decode($deviceDataIos['today_active_device'],true));
// 启动机型
// $hoursmodel = $device->model(['create_time'=>['between',[$starttime,$endtime]]]);
$hoursmodel = array_merge(json_decode($deviceDataAnd['today_model_device'],true),json_decode($deviceDataIos['today_model_device'],true));
foreach($hours as $v) {
foreach($hoursnews as $h) {
$time = explode(' ',$h['time']);
if ($time[1] == $v){
$data['news'][$h['version']==1?'and':'ios'][$v]+= (integer)$h['news'];
}
}
foreach($hoursactive as $h) {
$time = explode(' ',$h['time']);
if ($time[1] == $v){
$data['active'][$h['version']==1?'and':'ios'][$v] += (integer)$h['active'];
}
}
}
foreach($hoursmodel as $k=>$h) {
$data['xmodel'][$h['version']==1?'and':'ios'][] = "'".$h['model']."'";
$data['model'][$h['version']==1?'and':'ios'][$h['model']] = (integer)$h['count'];
}
} else {
$datelist = get_date_list($starttime,$endtime,$num==7?4:1);
$day_count = count($datelist);
$data['date'] = $datelist;
$data['hours'] = 0;
foreach($datelist as $k => $v) {
$data['news']['ios'][$v] = 0;
$data['news']['and'][$v] = 0;
$data['active']['ios'][$v] = 0;
$data['active']['and'][$v] = 0;
}
$newData = M('device_statistics','tab_')
->field("new_device as news,version,FROM_UNIXTIME(time,'%Y-%m-%d') as time")
->where(['time'=>['between',[$starttime,$endtime]],'new_device'=>['neq','0']])
->group('time,version')
->select();
// 新增设备
// $news = $device->news_on_time(['create_time'=>['between',[$starttime,$endtime]]],'news',$num==7?2:1,'time,version');
$news = $newData;
$activeData = M('device_statistics','tab_')
->field("active_device as active,version,FROM_UNIXTIME(time,'%Y-%m-%d') as time")
->where(['time'=>['between',[$starttime,$endtime]],'active_device'=>['neq','0']])
->group('time,version')
->select();
// 活跃设备
// $active = $device->active_on_time(['create_time'=>['between',[$starttime,$endtime]]],'active',$num==7?2:1,'time,version');
$active = $activeData;
// 启动机型
$modelData = M('device_statistics','tab_')
->field("model")
->where(['time'=>['between',[$starttime,$endtime]]])
->select();
$modelNew = [];
$unique_code = [];
foreach($modelData as $key => $value) {
$resolveData = json_decode($value['model'],true);
// dump($resolveData);
foreach($resolveData as $k => $v) {
if (!isset($modelNew[$v['model']][$v['version']])) {
$modelNew[$v['model']][$v['version']] = 1;
$unique_code[$v['unique_code']] = 1;
} else if(!$unique_code[$v['unique_code']]){
$modelNew[$v['model']][$v['version']]++;
$unique_code[$v['unique_code']] = 1;
// array_push($unique_code,$v['unique_code']);
}
}
}
$unique_code = [];
$modelNewData = [];
$modelKey = 0;
foreach($modelNew as $key => $value) {
$modelNewData[$modelKey]['model'] = $key;
foreach($value as $k => $v) {
$modelNewData[$modelKey]['version'] = $k;
$modelNewData[$modelKey]['count'] = $v;
}
$modelKey++;
}
$last_names = array_column($modelNewData,'count');
array_multisort($last_names,SORT_DESC,$modelNewData);
// dump($modelNewData);
// die();
// $model = $device->model(['create_time'=>['between',[$starttime,$endtime]]]);
// dump($model);die();
$model = $modelNewData;
foreach($datelist as $v) {
foreach($news as $h) {
if ($v == $h['time']) {
$data['news'][$h['version']==1?'and':'ios'][$v] += (integer)$h['news'];
}
}
foreach($active as $h) {
if ($v == $h['time']) {
$data['active'][$h['version']==1?'and':'ios'][$v] += (integer)$h['active'];
}
}
}
foreach($model as $k=>$h) {
$data['xmodel'][$h['version']==1?'and':'ios'][] = "'".$h['model']."'";
$data['model'][$h['version']==1?'and':'ios'][$h['model']] = (integer)$h['count'];
}
}
foreach($data as $k => $v) {
if (is_array($v)) {
if ($k == 'date'){
$data[$k] = '"'.implode('","',$v).'"';
$table[$k] = $v;
}elseif($k == 'xmodel'){
$table[$k]['ios'] = $v['ios'];
$table[$k]['and'] = $v['and'];
$data[$k]['ios'] = implode(',',$v['ios']);
$data[$k]['and'] = implode(',',$v['and']);
}elseif($k == 'model'){
$table[$k]['ios'] = $v['ios'];
$table[$k]['and'] = $v['and'];
$tempexport=[];
foreach($v['ios'] as $t => $s) {
$tempexport[]=['model'=>$t,'count'=>$s,'version'=>'ios'];
}
foreach($v['and'] as $t => $s) {
$tempexport[]=['model'=>$t,'count'=>$s,'version'=>'android'];
}
$export[$k]=$tempexport;
$data[$k]['ios'] = implode(',',$v['ios']);
$data[$k]['and'] = implode(',',$v['and']);
}else{
$sum = 0;$x='';$y=0;$tempexport=[];$count=0;
foreach($v['ios'] as $t => $s){
$sum += $s;$count++;
if($data['hours']==1){
if ($t%2==1) {$tab['ios'][$x.'~'.$t] = $y+$s;$x='';$y=0;}else{$x .= $t;$y += $s;}
$tempexport[]=['time'=>$start.' '.(substr($t,0,2)).':00','count'=>$s,'version'=>'ios'];
}else{
$tempexport[]=['time'=>$t,'count'=>$s,'version'=>'ios'];
}
}
foreach($v['and'] as $t => $s){
$sum += $s;$count++;
if($data['hours']==1){
if ($t%2==1) {$tab['and'][$x.'~'.$t] = $y+$s;$x='';$y=0;}else{$x .= $t;$y += $s;}
$tempexport[]=['time'=>$start.' '.(substr($t,0,2)).':00','count'=>$s,'version'=>'android'];
}else{
$tempexport[]=['time'=>$t,'count'=>$s,'version'=>'android'];
}
}
if($data['hours']==1){
$table[$k]=$tab;
$export['average'][$k]=$table['average'][$k]=$sum;
}else{
$table[$k] = $v;
$export['average'][$k]=$table['average'][$k]=round($sum/$day_count,2);
}
$export['sum'][$k] = $table['sum'][$k]=$sum;
$export[$k]=$tempexport;
$data[$k]['ios'] = implode(',',$v['ios']);
$data[$k]['and'] = implode(',',$v['and']);
}
}
}
if ($start != $end) {
$table['duplicate']['active'] = $this->getActiveDeviceNum(['time'=>array('between',[$starttime,$endtime])]);
$table['average']['active'] = number_format($table['duplicate']['active']/(((($endtime+1)-$starttime)/86400)),2,'.','');
// var_dump($endtime-$starttime);die();
} else {
$table['duplicate']['active'] = $table['sum']['active'];
}
@file_put_contents(RUNTIME_PATH.'/device_data_foldline.txt',json_encode($export));
if ($flag) {
$data['table'] = $table;
echo json_encode($data);
} else {
$this->assign('foldline',$data);
$this->assign('table',$table);
$this->assign('num',$num);
}
}
}