php 遇到问题记录(1)

2020-12-28 23:28

阅读:759

标签:rom   img   mobile   with   登录   define   usermod   roo   guid   

1.php时间及时间戳

php
echo date("Y/m/d") . "
"; echo date("Y.m.d") . "
"; echo date("Y-m-d"); //时间戳 $t=time(); echo($t . "
"); echo(date("Y-m-d",$t)); ?>

2.php JSON函数格式转换

技术图片

 

 

 

php
//php数组转化成JSON格式数组
   $arr = array(‘a‘ => 1, ‘b‘ => 2, ‘c‘ => 3, ‘d‘ => 4, ‘e‘ => 5);
   echo json_encode($arr);//{"a":1,"b":2,"c":3,"d":4,"e":5}
?>

技术图片

 

PHP json_decode() 函数用于对 JSON 格式的字符串进行解码,并转换为 PHP 变量。

php
//解码json数组
   $json = ‘{"a":1,"b":2,"c":3,"d":4,"e":5}‘;

   var_dump(json_decode($json));
   var_dump(json_decode($json, true));
?>

3.php多维数组

php
// 二维数组:
$sites = array
(
     "runoob"=>array
    (
        "菜鸟教程",
        "http://www.runoob.com"
    ),
    "google"=>array
    (
        "Google 搜索",
        "http://www.google.com"
    ),
    "taobao"=>array
    (
        "淘宝",
        "http://www.taobao.com"
    ) 
);
print_r($sites[‘runoob‘][0] . ‘地址为:‘ . $sites[‘runoob‘][1];);
?> 

 

4.PHP tp5.0 去重 distinct和group by

//利用distinct方法去重
$data=$test_data->Distinct(true)->field(‘descriprion‘)->order(‘description desc‘)->select();
//利用group方法去重
$data=$test_data->group(‘description‘)->order(‘description desc‘)->select();

//GROUP方法也是连贯操作方法之一,通常用于结合合计函数,根据一个或多个列对结果集进//行分组 。
//
//group方法只有一个参数,并且只能使用字符串。
//
//例如,我们都查询结果按照用户id进行分组统计:
Db::table(‘think_user‘)
    ->field(‘user_id,username,max(score)‘)
    ->group(‘user_id‘)
    ->select();

//生成的SQL语句是:SELECT user_id,username,max(score) FROM think_score GROUP BY user_id

5.查询不同表达式的地址

https://www.kancloud.cn/manual/thinkphp5_1/354004

6.打印错误信息

dump($_GPC);die;

 

任务列表相关:

php
/**
 * @author Yieldtop
 *
 **/

defined(‘IN_IA‘) or exit(‘Access Denied‘);
global $_GPC;
include_once IA_ROOT.‘/addons/‘.$_GPC[‘m‘].‘/common/base.php‘;

class task extends base {
     // 新增任务
    public function addtask() {
//         global $_GPC, $_W;
//         $ins=0;
//         $data = $_GPC[‘row‘]
//         $ins=db(‘mz_task‘)->insert($data);
        
//         $this->success($data);
        
        // if($result){
        //     //设置成功后跳转页面的地址,默认的返回页面是$_SERVER[‘HTTP_REFERER‘]
        //     $this->success(‘新增成功‘, ‘User/list‘);
        // } else {
        //     //错误页面的默认跳转页面是返回前一页,通常不需要设置
        //     $this->error(‘新增失败‘);
        // }
        
        global $_GPC, $_W;
        // dump($_GPC);die;
        $data=[];
        $data[‘mobile‘]=$_GPC[‘mobile‘];
        $data[‘type‘]=$_GPC[‘type‘];
        $data[‘action‘]=$_GPC[‘action‘];
        $data[‘qty‘]=$_GPC[‘qty‘];
        $data[‘price‘]=$_GPC[‘price‘];
        $data[‘content‘]=$_GPC[‘content‘];
        $data[‘day‘]=$_GPC[‘day‘];
        $data[‘pics‘]=$_GPC[‘pics‘];
        $data[‘createtime‘]=time();
        
        $ins=0;
        $ins=db(‘mz_task‘)->insert($data);
        
        $this->success($data);
        
    }
    
    // 任务查询
    public function tasktype() {
        global $_GPC, $_W;
        if (empty($_W[‘fans‘][‘nickname‘])) {
            mc_oauth_userinfo();
        }
        $pagesize = 10;
        $lists = db(‘mz_tasktype‘)->select();
        $this->success($lists);
    }
    // 任务行为
    public function action() {
        global $_GPC, $_W;
        if (empty($_W[‘fans‘][‘nickname‘])) {
            mc_oauth_userinfo();
        }
        $pagesize = 10;
        $lists = db(‘mz_action‘)->select();
        $this->success($lists);
    }
    //总任务列表
    public function index() {
        global $_GPC, $_W;
        $where=[];
        if($_GPC[‘type‘]){  
            $where[‘type‘] = $_GPC[‘type‘];  
        }
        if (empty($_W[‘fans‘][‘nickname‘])) {
            mc_oauth_userinfo();
        }
        $pagesize = 10;
        $lists = db(‘mz_task‘)->where(‘uniacid‘,$_W[‘uniacid‘])->where($where)->page($_GPC[‘page‘],$_GPC[‘limit‘])->select();
        $this->success($lists);
    }
    private function create_guid() {
    $charid = strtoupper(md5(uniqid(mt_rand(), true)));
    $hyphen=‘‘;
    $uuid = 
    substr($charid, 0, 8).$hyphen
    .substr($charid, 8, 4).$hyphen
    .substr($charid,12, 4).$hyphen
    .substr($charid,16, 4).$hyphen
    .substr($charid,20,12);
    return $uuid;
}
    public function test()
    {
        global $_GPC, $_W;
        dump($_W[‘fans‘]);
        echo $this->create_guid();
        die;
        $lists = db(‘mz_task‘)->select();
        print_r($lists);
    }

}

 

 

示例:

 public function fanscount($p_id=‘‘,$nickname=‘‘,$litpic=‘‘,$scene=‘‘)
    {
        $data=[];
        $today=date("Y-m-d",time());
        //查找之前连续的起始点
        $tdaytime=strtotime($today);
        
        //总粉丝数
        $data[‘total‘] = Db::name(‘v_myteam‘)->group(‘open_id‘)->where(‘p_id‘,$p_id)->count();
        //直邀粉丝
        $data[‘directtotal‘] = Db::name(‘v_myteam‘)->group(‘open_id‘)->where(‘p_id‘,$p_id)->where(‘litpic‘,‘not null‘)->count();
         return json([‘code‘=>0,‘msg‘=>‘成功‘,‘data‘=>$data]);
    }

参考案例:

php

/**
 * description:
 * Date: 2020-02-29
 * Time: 12:25
 */

namespace app\api\controller;

use app\common\model\UserInfo;
use app\common\model\Users;
use app\common\model\UserToken;
use Exception;
use think\Request;
use think\Db;

class User extends Base
{
    /**
     * @var Users
     */
    private $userModel;
    /**
     * @var UserInfo
     */
    private $userInfoModel;
    /**
     * @var UserToken
     */
    private $userTokenModel;
    protected $noNeedRightAction = [‘bindWeChat‘, ‘bindWeChatII‘, ‘loginWithPhone‘,‘receive‘,‘getopenid‘];
    protected $noNeedLoginAction = [‘bindWeChat‘, ‘bindWeChatII‘, ‘loginWithPhone‘,‘receive‘,‘getopenid‘];

    public function _initialize()
    {
        parent::_initialize();

        $this->userModel = model(‘common/Users‘);

        $this->userInfoModel = model(‘common/UserInfo‘);

        $this->userTokenModel = model(‘common/UserToken‘);
    }
    
    //获取openid
    public function getopenid($code,$all=0)
    {
        //$code = $_GET[‘code‘];//小程序传来的code值
        //$url = ‘https://api.weixin.qq.com/sns/jscode2session?appid="你的APPID"&secret="你的app密钥"&js_code=‘ . $code . ‘&grant_type=authorization_code‘;
        $url = ‘https://api.weixin.qq.com/sns/jscode2session?appid=‘ . config(‘wechat.appid‘) . ‘&secret=‘ .
          config(‘wechat.secret‘) . ‘&js_code=‘ . $code . ‘&grant_type=authorization_code‘;;
        //yourAppid为开发者appid.appSecret为开发者的appsecret,都可以从微信公众平台获取;
        $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据,推荐使用curl
        $json = json_decode($info);//对json数据解码
        $arr = get_object_vars($json);
       // dump($arr);die;
        $openid = $arr[‘openid‘];
        if($all)
        {
            return json([‘code‘=>0,‘msg‘=>‘成功.‘,‘data‘=>$arr]);
        }
        else
        {
            return json([‘code‘=>0,‘msg‘=>‘成功!‘,‘data‘=>$openid]);
        }
       
    }
    
    //分享的小程序码接收到保存信息
    public function receive($openid=‘‘,$nickname=‘‘,$litpic=‘‘,$scene=‘‘)
    {
        
        //$fpc=file_put_contents($_SERVER[‘DOCUMENT_ROOT‘].‘/data.receive.txt‘,json_encode($_REQUEST));
        
        //分享得积分
        $oidcnt=Db::name(‘users‘)->where(‘open_id‘,$openid)->count();
        $oidcnt+=Db::name(‘points‘)->where(‘myopenid‘,$openid)->count();
        
        $sarr=explode(‘!‘,$scene);
        $cnt=Db::name(‘v_team‘)->where(‘open_id‘,$openid)->count();
        if($cnt) {return json([‘code‘=>1,‘msg‘=>‘已存在‘,‘data‘=>$data]);};
        $data=[
            ‘open_id‘=>$openid,‘nickname‘=>$nickname,‘scene‘=>$scene,‘litpic‘=>$litpic,‘p_id‘=>$sarr[1],‘add_time‘=>time()
            ];
            
            try {
            Db::startTrans();
            
                $ins=Db::name(‘user_share‘)->insert($data);
            
            //取当前日期
            $today=date("Y-m-d",time());
            $tdaytime=strtotime($today);
            
            $pdata=[];
            $pdata[‘openid‘]=Db::name(‘users‘)->where(‘id‘,$sarr[1])->value(‘open_id‘);
            $tsum=Db::name(‘v_points‘)->where(‘createtime‘,‘>=‘,$tdaytime)->where(‘type‘,‘share‘)->where(‘openid‘,$pdata[‘openid‘])->sum(‘num‘);
            
            if(!$oidcnt && $tsum) 
            {
                
                $pdata[‘uid‘]=$sarr[1];
                $pdata[‘openid‘]=Db::name(‘users‘)->where(‘id‘,$sarr[1])->value(‘open_id‘);
                $pdata[‘myopenid‘]=$openid;
                $pdata[‘aid‘]=$sarr[0];
                $pdata[‘type‘]=‘share‘;
                $pdata[‘num‘]=30;
                $pdata[‘createtime‘]=time();
                $inp=Db::name(‘points‘)->insert($pdata);
            }
        
            Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return json([‘code‘=>1,‘msg‘=>‘失败‘,‘data‘=>$data]);
            }
        
        return json([‘code‘=>0,‘msg‘=>‘成功‘,‘data‘=>$data]);
        
        /*if($ins)
        {
            return json([‘code‘=>0,‘msg‘=>‘成功‘,‘data‘=>$data]);
            //$this->success($data);
        }
        else
        {
            return json([‘code‘=>1,‘msg‘=>‘失败‘,‘data‘=>$data]);
        }*/
        
        
        
    }

    /**
     * 获取用户信息
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info()
    {
        $user = $this->userModel->field([
          ‘nickname‘,
          ‘litpic‘,
          ‘level_id‘,
          ‘id‘,
          ‘p_id‘
        ])->with(‘perfect‘)->findOrFail($this->uid);
        $user[‘level_text‘] = getLevelText($user->level_id);
        /*$subsidy = model(‘common/Subsidy‘)->where(‘uid‘, $this->uid)
                                          ->where(‘status‘, \app\common\model\Subsidy::STATUS_JIE_SUAN_FINISH)
                                          ->sum(‘receive_money‘);*/
                                          
        $subsidy_money=Db::name(‘subsidy_log‘)->where(‘from_uid‘, $this->uid)->sum(‘money‘);
                                          
        $commission = model(‘common/Commissions‘)
          ->where(‘uid‘, $this->uid)
          ->sum(‘money‘);
        
        $openid=Db::name(‘users‘)->where(‘id‘,$this->uid)->value(‘open_id‘);
        $sum_num=Db::name(‘v_points‘)->where(‘openid‘,$openid)->sum(‘num‘);  
          
        $user[‘finance‘] = [
          ‘total‘            => $subsidy_money + $commission,//$subsidy + $commission,
          ‘subsidy_money‘    => $subsidy_money,//$subsidy,
          ‘commission_money‘ => $commission,
          ‘integral_sum‘=>$sum_num
        ];

        return $this->responseSuccess($user);

    }

    /**
     * 完善用户信息
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function perfect(Request $request)
    {
        $data = $request->post();
        $this->validate($data, [
            //          ‘real_name‘      => ‘require‘,
            //          ‘phone‘          => ‘require‘,
            //          ‘card_type‘      => ‘require‘,
            //          ‘card_no‘        => ‘require‘,
            //          ‘city_name‘      => ‘require‘,
            //          ‘bank_no‘        => ‘require‘,
            //          ‘bank_name‘      => ‘require‘,
            //          ‘bank_account‘   => ‘require‘,
            //          ‘alipay_account‘ => ‘require‘,
        ]);
        $user = $this->userInfoModel->where(‘uid‘, $this->uid)->find();
        if ($user) {
            $this->userInfoModel->where(‘uid‘, $this->uid)->save($data);
        } else {
            $data[‘uid‘] = $this->uid;
            $this->userInfoModel->add($data);
        }

        return $this->responseSuccess();
    }

    /**
     * 微信小程序 绑定
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bindWeChat(Request $request)
    {
        $data = $request->post();
        $this->validate($data, [
            //          ‘openId‘    => ‘require‘,
            ‘nickName‘  => ‘require‘,
            ‘avatarUrl‘ => ‘require‘,
            ‘js_code‘   => ‘require‘
        ]);
        $url = ‘https://api.weixin.qq.com/sns/jscode2session?appid=‘ . config(‘wechat.appid‘) . ‘&secret=‘ .
          config(‘wechat.secret‘) . ‘&js_code=‘ . $data[‘js_code‘] . ‘&grant_type=authorization_code‘;;
        $res = json_decode(file_get_contents($url), true);
        if (isset($res[‘errcode‘]) && $res[‘errcode‘]) {
            return $this->responseSuccess(1, $res[‘errmsg‘]);
        }
        $data[‘openId‘] = $res[‘openid‘];
        try {
            $user = $this->userModel->where(‘open_id‘, $data[‘openId‘])->findOrFail();
            $uid = $user[‘id‘];
            $this->userModel->where(‘id‘, $user[‘id‘])->update([
                ‘nickname‘ => $data[‘nickName‘],
                ‘litpic‘   => $data[‘avatarUrl‘],
            ]);
        } catch (Exception $e) {
            if (isset($data[‘pid‘])) {
                $this->userModel->where(‘id‘, $data[‘pid‘])->findOrFail();
            }
            $uid = $this->userModel->insertGetId([
              ‘open_id‘  => $data[‘openId‘],
              ‘nickname‘ => $data[‘nickName‘],
              ‘litpic‘   => $data[‘avatarUrl‘],
              ‘p_id‘     => $data[‘pid‘] ?? ‘‘,
            ]);
        }
        $token = $this->userTokenModel->createToken($uid);
        $userToken = $this->userTokenModel->where(‘from‘, UserToken::WE_CHART)
                                          ->where(‘uid‘, $uid)
                                          ->find();
        if ($userToken) {
            $userToken->token = $token;
            $userToken->expires_time = date(‘Y-m-d H:i:s‘, time() + 86400 * 2);
            $userToken->save();
        } else {
            $this->userTokenModel->insert([
              ‘uid‘          => $uid,
              ‘from‘         => UserToken::WE_CHART,
              ‘token‘        => $token,
              ‘expires_time‘ => date(‘Y-m-d H:i:s‘, time() + 86400 * 2)
            ]);
        }

        $userToken = $this->userTokenModel->where(‘from‘, UserToken::WE_CHART)
                                          ->where(‘uid‘, $uid)
                                          ->findOrFail();

        $data = $userToken;
        return $this->responseSuccess($data);
    }

    /**
     * 微信小程序 绑定
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bindWeChatII(Request $request)
    {
        $data = $request->post();
        $this->validate($data, [
            //          ‘openId‘    => ‘require‘,
            ‘nickName‘  => ‘require‘,
            ‘avatarUrl‘ => ‘require‘,
            ‘js_code‘   => ‘require‘
        ]);
        $url = ‘https://api.weixin.qq.com/sns/jscode2session?appid=‘ . config(‘wechat.appid‘) . ‘&secret=‘ .
          config(‘wechat.secret‘) . ‘&js_code=‘ . $data[‘js_code‘] . ‘&grant_type=authorization_code‘;;
        $res = json_decode(file_get_contents($url), true);
        if (isset($res[‘errcode‘]) && $res[‘errcode‘]) {
            return $this->responseSuccess(1, $res[‘errmsg‘]);
        }
        $data[‘openId‘] = $res[‘openid‘];
        try {
            $user = $this->userModel->where(‘open_id‘, $data[‘openId‘])->findOrFail();
            $uid = $user[‘id‘];
            $this->userModel->where(‘id‘, $user[‘id‘])->update([
                ‘nickname‘ => $data[‘nickName‘],
                ‘litpic‘   => $data[‘avatarUrl‘],
            ]);
        } catch (Exception $e) {
            if (isset($data[‘pid‘])) {
                $this->userModel->where(‘id‘, $data[‘pid‘])->findOrFail();
            }
            $uid = $this->userModel->insertGetId([
              ‘open_id‘  => $data[‘openId‘],
              ‘nickname‘ => $data[‘nickName‘],
              ‘litpic‘   => $data[‘avatarUrl‘],
              ‘p_id‘     => $data[‘pid‘] ?? ‘‘,
            ]);
        }
        $token = $this->userTokenModel->createToken($uid);
        $userToken = $this->userTokenModel->where(‘from‘, UserToken::WE_CHART)
                                          ->where(‘uid‘, $uid)
                                          ->find();
        if ($userToken) {
            $userToken->token = $token;
            $userToken->expires_time = date(‘Y-m-d H:i:s‘, time() + 86400 * 2);
            $userToken->save();
        } else {
            $this->userTokenModel->insert([
              ‘uid‘          => $uid,
              ‘from‘         => UserToken::WE_CHART,
              ‘token‘        => $token,
              ‘expires_time‘ => date(‘Y-m-d H:i:s‘, time() + 86400 * 2)
            ]);
        }

        $userToken = $this->userTokenModel->where(‘from‘, UserToken::WE_CHART)
                                          ->where(‘uid‘, $uid)
                                          ->findOrFail();

        $data = $userToken;
        return $this->responseSuccess([‘user‘ => $data, ‘raw‘ => $res]);
    }



    /**
     * 我的团队
     * @return \think\response\Json
     */
    public function team(Request $request)
    {
        $page = $request->get(‘page‘, 1);
        //$data = $this->userModel->where(‘p_id‘, $this->uid)->page($page)->select();//->page($page)
        $data = Db::name(‘v_team‘)->distinct(true)->where(‘p_id‘, $this->uid)->order(‘nickname desc‘)->select();
        
        $fpc=file_put_contents($_SERVER[‘DOCUMENT_ROOT‘].‘/data.vsql.txt‘,json_encode(Db::name(‘v_team‘)->getLastSql()));
        
        foreach($data as $k=>$v)
        {
            if(!$v[‘nickname‘])
            {
                $data[$k][‘nickname‘]=‘未登录用户:‘.substr($v[‘open_id‘],0,6);
            }
        }
        
        return $this->responseSuccess($data);
    }

    /**
     * 团队人数和佣金金额
     * @return \think\response\Json
     */
    public function getTeamInfo()
    {
        $uidArr = $this->userModel->where(‘p_id‘, $this->uid)->column(‘id‘);
        $data = [
          ‘childrenNum‘          => count($uidArr),
          ‘recommend_commission‘ => model(‘common/Commissions‘)
            ->where(‘uid‘, $this->uid)
            ->where(‘type‘, 2)
            ->sum(‘money‘)
        ];
        
        
        
        return $this->responseSuccess($data);
    }

    public function loginWithPhone(Request $request)
    {
        $data = $request->post();
        $this->validate($data, [
          ‘nickName‘ => ‘require‘,
          ‘phone‘    => ‘require‘,
          ‘code‘     => ‘require‘
        ]);
        if (cache(‘login_‘ . $data[‘phone‘]) != $data[‘code‘]) {
            //return $this->responseJson(1, ‘验证码失效‘);
        }
        try {
            $user = $this->userModel->where(‘mobile‘, $data[‘phone‘])->findOrFail();
            $uid = $user[‘id‘];
        } catch (Exception $e) {
            if (isset($data[‘p_id‘])) {
                $this->userModel->where(‘id‘, $data[‘p_id‘])->findOrFail();
            }
            $uid = $this->userModel->insertGetId([
              ‘mobile‘   => $data[‘phone‘],
              ‘nickname‘ => $data[‘nickName‘],
            ]);
        }
        $token = $this->userTokenModel->createToken($uid);
        $userToken = $this->userTokenModel->where(‘from‘, UserToken::WE_CHART)
                                          ->where(‘uid‘, $uid)
                                          ->find();
        if ($userToken) {
            $userToken->token = $token;
            $userToken->expires_time = date(‘Y-m-d H:i:s‘, time() + 86400 * 2);
            $userToken->save();
        } else {
            $this->userTokenModel->insert([
              ‘uid‘          => $uid,
              ‘from‘         => UserToken::WE_CHART,
              ‘token‘        => $token,
              ‘expires_time‘ => date(‘Y-m-d H:i:s‘, time() + 86400 * 2)
            ]);
        }

        $userToken = $this->userTokenModel->where(‘from‘, UserToken::WE_CHART)
                                          ->where(‘uid‘, $uid)
                                          ->findOrFail();

        $data = $userToken;
        return $this->responseSuccess($data);


    }
}

 

thinkPHP开发手册:https://www.kancloud.cn/manual/thinkphp5_1/354004

 

php 遇到问题记录(1)

标签:rom   img   mobile   with   登录   define   usermod   roo   guid   

原文地址:https://www.cnblogs.com/xiaotingbaobao/p/13822183.html


评论


亲,登录后才可以留言!