博客

  • 周期性每日签到逻辑(7天)

    /*     
         * 获取每日任务页面签到部分数据
         * $openid 用户openID
         * */
        
        public function zkGetSign($openid)
        {
            global $_W;
            global $_GPC;
            if(empty($openid)){
                return '';
            }
            $day0 = strtotime(date('Y-m-d'));
            $daynow = time();//当前时间戳
            $isSign = 0; //是否已签到
            $sign_row = pdo_fetch('select id  from ' . tablename('ewei_shop_sns_sign_in') . ' where uniacid=:uniacid and openid=:openid and ( signintime>:day0 and signintime<:daynow ) limit 1 ', array(':uniacid' => $_W[‘uniacid’],':openid' => $openid, ':day0' => $day0, ':daynow' => $daynow));
            if(!empty($sign_row)){//当日已签到
                $isSign = 1;
            }
            //周期内签到天数
            $signDay = 0;
            $sign_history = pdo_fetch('select *  from ' . tablename('ewei_shop_sns_sign_in') . ' where uniacid=:uniacid and openid=:openid order by signintime desc limit 1 ', array(':uniacid' => $_W[‘uniacid’],':openid' => $openid));
            if(!empty($sign_history)){
                $day = $this->diffBetweenTwoDays(date('Y-m-d',$daynow),date('Y-m-d',$sign_history[‘signintime’]));
                if($day <= 1){
                    $signDay = $sign_history[‘signinday’];
                    if($signDay == 7){
                        $signDay = 0;
                    }
                }
            }
            $snsSet = m("common")->getPluginset("sns");//sns配置信息
            //签到奖励积分数组
            $sign_arr = array(intval($snsSet[‘qd_day1’]),intval($snsSet[‘qd_day2’]),intval($snsSet[‘qd_day3’]),intval($snsSet[‘qd_day4’]),intval($snsSet[‘qd_day5’]),intval($snsSet[‘qd_day6’]),intval($snsSet[‘qd_day7’]));
            
            //构建签到进度数据
            $signData =array();
            for($i=1;$i<=7;$i++){
                $signData[$i][‘day’] = $i;
                $signData[$i][‘credit’] = $sign_arr[$i-1];
                if($i<=$signDay){//已签
                    $signData[$i][‘isSign’] = 1;
                }else{//未签
                    $signData[$i][‘isSign’] = 0;
                }
            }
            
            $res = array();
            $res[‘signDay’] = $signDay; //周期内签到天数
            $res[‘isSign’] = $isSign; //是否已签到
            $res[‘nowCredit’] = $this->getCredit($openid); //当前积分
            $res[‘nowMonth’] = date('m',$daynow); //当前月
            $res[‘nowDay’] = date('d',$daynow); //当前日
            $res[‘signData’] = $signData; //签到进度数据
            return $res;
        }
        
        /*     
         * 用户签到,日签一次
         * $openid 用户openID
         * */
        
        public function zkSetSign($openid)
        {
            global $_W;
            global $_GPC;
            if(empty($openid)){
                return '';
            }
            $day0 = strtotime(date('Y-m-d'));
            $daynow = time();
            $sign_row = pdo_fetch('select id  from ' . tablename('ewei_shop_sns_sign_in') . ' where uniacid=:uniacid and openid=:openid and ( signintime>:day0 and signintime<:daynow ) limit 1 ', array(':uniacid' => $_W[‘uniacid’],':openid' => $openid, ':day0' => $day0, ':daynow' => $daynow));
            if(empty($sign_row)){//当日未签到
                $credit = 0;
                $snsSet = m("common")->getPluginset("sns");//sns配置信息
                //签到奖励积分数组
                $sign_arr = array(intval($snsSet[‘qd_day1’]),intval($snsSet[‘qd_day2’]),intval($snsSet[‘qd_day3’]),intval($snsSet[‘qd_day4’]),intval($snsSet[‘qd_day5’]),intval($snsSet[‘qd_day6’]),intval($snsSet[‘qd_day7’]));
                $sign_history = pdo_fetch('select *  from ' . tablename('ewei_shop_sns_sign_in') . ' where uniacid=:uniacid and openid=:openid order by signintime desc limit 1 ', array(':uniacid' => $_W[‘uniacid’],':openid' => $openid));
                if(empty($sign_history)){
                    $credit = $sign_arr[0];
                    $totalday = $signinday = 1;
                    $credits_sum = $credit;
                }else{
                    $day = $this->diffBetweenTwoDays(date('Y-m-d',$daynow),date('Y-m-d',$sign_history[‘signintime’]));
                    if($day > 1){//漏签了
                        $credit = $sign_arr[0];
                        $totalday = $signinday = 1;
                        $credits_sum = $credit + $sign_history[‘credits_sum’];
                    }else{
                        if($sign_history[‘signinday’]==7){
                            $credit = $sign_arr[0];
                            $signinday = 1 ;
                        }else{
                            $credit = $sign_arr[$sign_history[‘signinday’]];
                            $signinday = 1 + $sign_history[‘signinday’];
                        }
                        $credits_sum = $credit + $sign_history[‘credits_sum’];
                        $totalday = $sign_history[‘totalday’] + 1;
                    }
                }
                //插入签到记录
                $data = array();
                $data[‘credits’] = $credit;
                $data[‘openid’] = $openid;
                $data[‘uniacid’] = $_W[‘uniacid’];
                $data[‘signinday’] = $signinday;
                $data[‘credits_sum’] = $credits_sum;
                $data[‘signintime’] = $daynow;
                $data[‘totalday’] = $totalday;
                pdo_insert('ewei_shop_sns_sign_in', $data);
                $resid = pdo_insertid();
                
                //发放积分
                $log = '(获得 '.date('Y年m月d日',$daynow). ' 签到奖励,连续签到 '.$signinday.' 天,奖励 '.$credit.' 积分)';
                $this->zkSetCredits($openid,$credit,'credit1',$log);
                
                return $resid;
            }else{
                return '您今天已签到,无需重复签到';
            }
            
            $res = array();
            $res[‘sign_arr’] = $sign_arr;
            $res[‘snsSet’] = $snsSet;
            return $res;
        }

  • PHP Excel 导入导出 示例 附:配套PHPExcel插件源码

    //excel导入导出
        
        public function column_str($key)
        {
            $array = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ', 'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ', 'CA', 'CB', 'CC', 'CD', 'CE', 'CF', 'CG', 'CH', 'CI', 'CJ', 'CK', 'CL', 'CM', 'CN', 'CO', 'CP', 'CQ', 'CR', 'CS', 'CT', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DA', 'DB', 'DC', 'DD', 'DE', 'DF', 'DG', 'DH', 'DI', 'DJ', 'DK', 'DL', 'DM', 'DN', 'DO', 'DP', 'DQ', 'DR', 'DS', 'DT', 'DU', 'DV', 'DW', 'DX', 'DY', 'DZ', 'EA', 'EB', 'EC', 'ED', 'EE', 'EF', 'EG', 'EH', 'EI', 'EJ', 'EK', 'EL', 'EM', 'EN', 'EO', 'EP', 'EQ', 'ER', 'ES', 'ET', 'EU', 'EV', 'EW', 'EX', 'EY', 'EZ');
            return $array[$key];
        }

        public function column($key, $columnnum = 1)
        {
            return $this->column_str($key) . $columnnum;
        }

        /**
         * 导出Excel
         * @param type $list
         * @param type $params
         */
        public function export($list, $params = array())
        {
            if (PHP_SAPI == 'cli') {
                exit('This example should only be run from a Web Browser');
            }

            require_once IA_ROOT . '/framework/library/phpexcel/PHPExcel.php';
            $excel = new PHPExcel();
            $excel->getProperties()->setCreator('weichengtech')->setLastModifiedBy('weichengtech')->setTitle('Office 2007 XLSX Test Document')->setSubject('Office 2007 XLSX Test Document')->setDescription('Test document for Office 2007 XLSX, generated using PHP classes.')->setKeywords('office 2007 openxml php')->setCategory('report file');
            $sheet = $excel->setActiveSheetIndex(0);
            $rownum = 1;

            foreach ($params[‘columns’] as $key => $column) {
                $sheet->setCellValue($this->column($key, $rownum), $column[‘title’]);

                if (!empty($column[‘width’])) {
                    $sheet->getColumnDimension($this->column_str($key))->setWidth($column[‘width’]);
                }
            }

            ++$rownum;
            $len = count($params[‘columns’]);

            foreach ($list as $row) {
                $i = 0;

                while ($i < $len) {
                    $value = (isset($row[$params[‘columns’][$i][‘field’]]) ? $row[$params[‘columns’][$i][‘field’]] : '');
                    $sheet->setCellValue($this->column($i, $rownum), $value);
                    ++$i;
                }

                ++$rownum;
            }

            $excel->getActiveSheet()->setTitle($params[‘title’]);
            $filename = urlencode($params[‘title’] . '-' . date('Y-m-d H:i', time()));
            ob_end_clean();
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
            header('Cache-Control: max-age=0');
            $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
            $this->SaveViaTempFile($writer);
            exit();
        }

        /**
         * @param $objWriter PHPExcel_Writer_IWriter
         */
        public function SaveViaTempFile($objWriter)
        {
            $filePath = '' . rand(0, getrandmax()) . rand(0, getrandmax()) . '.tmp';
            $objWriter->save($filePath);
            readfile($filePath);
            unlink($filePath);
        }

        /**
         * 生成模板文件Excel
         * @param type $list
         * @param type $params
         */
        public function temp($title, $columns = array())
        {
            if (PHP_SAPI == 'cli') {
                exit('This example should only be run from a Web Browser');
            }

            require_once IA_ROOT . '/framework/library/phpexcel/PHPExcel.php';
            $excel = new PHPExcel();
            $excel->getProperties()->setCreator('weichengtech')->setLastModifiedBy('weichengtech')->setTitle('Office 2007 XLSX Test Document')->setSubject('Office 2007 XLSX Test Document')->setDescription('Test document for Office 2007 XLSX, generated using PHP classes.')->setKeywords('office 2007 openxml php')->setCategory('report file');
            $sheet = $excel->setActiveSheetIndex(0);
            $rownum = 1;

            foreach ($columns as $key => $column) {
                $sheet->setCellValue($this->column($key, $rownum), $column[‘title’]);

                if (!empty($column[‘width’])) {
                    $sheet->getColumnDimension($this->column_str($key))->setWidth($column[‘width’]);
                }
            }

            ++$rownum;
            $len = count($columns);
            $k = 1;

            while ($k <= 5000) {
                $i = 0;

                while ($i < $len) {
                    $sheet->setCellValue($this->column($i, $rownum), '');
                    ++$i;
                }

                ++$rownum;
                ++$k;
            }

            $excel->getActiveSheet()->setTitle($title);
            $filename = urlencode($title);
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
            header('Cache-Control: max-age=0');
            $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
            $writer->save('php://output');
            exit();
        }

        public function import($excefile)
        {
            global $_W;
            require_once IA_ROOT . '/framework/library/phpexcel/PHPExcel.php';
            require_once IA_ROOT . '/framework/library/phpexcel/PHPExcel/IOFactory.php';
            require_once IA_ROOT . '/framework/library/phpexcel/PHPExcel/Reader/Excel5.php';
            $path = IA_ROOT . '/addons/zhls_sun/data/tmp/';

            if (!is_dir($path)) {
                load()->func('file');
                mkdirs($path, '0777');
            }

            $filename = $_FILES[$excefile][‘name’];
            $tmpname = $_FILES[$excefile][‘tmp_name’];

            if (empty($tmpname)) {
                message('请选择要上传的Excel文件!', '', 'error');
            }

            $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            if (($ext != 'xlsx') && ($ext != 'xls')) {
                message('请上传 xls 或 xlsx 格式的Excel文件!', '', 'error');
            }

            $file = time() . $_W[‘uniacid’] . '.' . $ext;
            $uploadfile = $path . $file;
            $result = move_uploaded_file($tmpname, $uploadfile);

            if (!$result) {
                message('上传Excel 文件失败, 请重新上传!', '', 'error');
            }

            $reader = PHPExcel_IOFactory::createReader($ext == 'xls' ? 'Excel5' : 'Excel2007');
            $excel = $reader->load($uploadfile);
            $sheet = $excel->getActiveSheet();
            $highestRow = $sheet->getHighestRow();
            $highestColumn = $sheet->getHighestColumn();
            $highestColumnCount = PHPExcel_Cell::columnIndexFromString($highestColumn);
            $values = array();
            $row = 2;

            while ($row <= $highestRow) {
                $rowValue = array();
                $col = 0;

                while ($col < $highestColumnCount) {
                    $rowValue[] = $sheet->getCellByColumnAndRow($col, $row)->getValue();
                    ++$col;
                }

                $values[] = $rowValue;
                ++$row;
            }

            return $values;
        }
            
        //excel导入导出

    附:以上代码配套的PHPExcel插件源码,扫码关注,回复关键字‘PHPExcel’获取

  • PHP汉字转拼音

     /*汉字换取拼音*/

    public function getPinyin($_String, $lstring, $flag = 1)
        {
            if ($flag) {
                $_Code = 'utf-8';
            }
            else {
                $_Code = 'gb2312';
            }

            if (!empty($lstring)) {
                $_String = $lstring . $_String;
            }

            $_DataKey = 'a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha' . '|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|' . 'cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er' . '|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui' . '|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang' . '|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang' . '|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue' . '|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne' . '|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen' . '|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang' . '|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|' . 'she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|' . 'tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu' . '|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you' . '|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|' . 'zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo';
            $_DataValue = '-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990' . '|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725' . '|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263' . '|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003' . '|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697' . '|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211' . '|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922' . '|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468' . '|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664' . '|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407' . '|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959' . '|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652' . '|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369' . '|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128' . '|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914' . '|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645' . '|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149' . '|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087' . '|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658' . '|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340' . '|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888' . '|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585' . '|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847' . '|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055' . '|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780' . '|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274' . '|-10270|-10262|-10260|-10256|-10254';
            $_TDataKey = explode('|', $_DataKey);
            $_TDataValue = explode('|', $_DataValue);
            $_Data = ('5.0' <= PHP_VERSION ? array_combine($_TDataKey, $_TDataValue) : $this->_Array_Combine($_TDataKey, $_TDataValue));
            arsort($_Data);
            reset($_Data);

            if ($_Code != 'gb2312') {
                $_String = $this->_U2_Utf8_Gb($_String);
            }

            $_Res = '';
            $i = 0;

            while ($i < strlen($_String)) {
                $_P = ord(substr($_String, $i, 1));

                if (160 < $_P) {
                    $_Q = ord(substr($_String, ++$i, 1));
                    $_P = (($_P * 256) + $_Q) – 65536;
                }

                $_Res .= $this->_Pinyin($_P, $_Data);
                ++$i;
            }

            return preg_replace('/[^a-z0-9]*/', '', $_Res);
        }

        public function _Pinyin($_Num, $_Data)
        {
            if ((0 < $_Num) && ($_Num < 160)) {
                return chr($_Num);
            }

            if (($_Num < -20319) || (-10247 < $_Num)) {
                return '';
            }

            foreach ($_Data as $k => $v) {
                if ($v <= $_Num) {
                    break;
                }
            }

            return $k;
        }

        public function _U2_Utf8_Gb($_C)
        {
            $_String = '';

            if ($_C < 128) {
                $_String .= $_C;
            }
            else if ($_C < 2048) {
                $_String .= chr(192 | ($_C >> 6));
                $_String .= chr(128 | ($_C & 63));
            }
            else if ($_C < 65536) {
                $_String .= chr(224 | ($_C >> 12));
                $_String .= chr(128 | (($_C >> 6) & 63));
                $_String .= chr(128 | ($_C & 63));
            }
            else {
                if ($_C < 2097152) {
                    $_String .= chr(240 | ($_C >> 18));
                    $_String .= chr(128 | (($_C >> 12) & 63));
                    $_String .= chr(128 | (($_C >> 6) & 63));
                    $_String .= chr(128 | ($_C & 63));
                }
            }

            return iconv('UTF-8', 'GB2312', $_String);
        }

        public function _Array_Combine($_Arr1, $_Arr2)
        {
            $i = 0;

            while ($i < count($_Arr1)) {
                $_Res[$_Arr1[$i]] = $_Arr2[$i];
                ++$i;
            }

            return $_Res;
        }

  • PHP中两种格式化输出数组的函数,解决var_dump();的眼花缭乱

    /**
     *第一种
     */

        function dump()
        {
            $args = func_get_args();
            foreach ($args as $val) {
                echo '<pre style="color: red">';
                var_dump($val);
                echo '</pre>';
            }
        }


    /*
    * 第二种
    */

    function dump($var, $echo=true, $label=null, $strict=true) {
        $label = ($label === null) ? '' : rtrim($label) . ' ';
        if (!$strict) {
            if (ini_get('html_errors')) {
                $output = print_r($var, true);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            } else {
                $output = $label . print_r($var, true);
            }
        } else {
            ob_start();
            var_dump($var);
            $output = ob_get_clean();
            if (!extension_loaded('xdebug')) {
                $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            }
        }
        if ($echo) {
            echo($output);
            return null;
        }else
            return $output;
    }

  • 评论消息时间显示(刚刚,X分钟前,X小时前,X天前)

    /**
             * 评论消息
             * @param $openid
             * @param $data
             */
            public function timeBefore($the_time)
            {
                $now_time = time();
                $dur = $now_time – $the_time;

                if ($dur < 0) {
                    return $the_time;
                }

                if ($dur < 60) {
                    return '刚刚';
                }

                if ($dur < 3600) {
                    return floor($dur / 60) . '分钟前';
                }

                if ($dur < 86400) {
                    return floor($dur / 3600) . '小时前';
                }

                if ($dur < 259200) {
                    return floor($dur / 86400) . '天前';
                }

                return date('m-d', $the_time);
            }

  • 人人商城推送消息示例

    public function sendMemberSnsUpgradeMessage($openid, $nickname, $oldlevel, $level)
            {
                $set = $this->getSet();
                $tm = $set[‘tm’];
                $datas[] = array('name' => '昵称', 'value' => $nickname);
                $datas[] = array(‘name’ => ‘新等级’, ‘value’ => $oldlevel[‘levelname’]);
                $datas[] = array(‘name’ => ‘旧等级’, ‘value’ => $level[‘levelname’]);
                $datas[] = array('name' => '时间', 'value' => date('Y-m-d H:i:s', time()));
                $remark = '
    [昵称]感谢您的支持,如有疑问请联系在线客服。';
                $text = '亲爱的' . $nickname . '您的社区等级已升级,详情请登录社区查看。';
                $title = '社区等级升级';
                $message = array(
                    'first'    => array('value' => '亲爱的' . $nickname . ',您的社区等级已升级', 'color' => '#ff0000'),
                    'keyword2' => array('title' => '处理进度', 'value' => $title, 'color' => '#000000'),
                    'keyword3' => array('title' => '处理内容', 'value' => '您的人人社区等级已升级成功', 'color' => '#000000'),
                    'keyword1' => array('title' => '业务类型', 'value' => '会员通知', 'color' => '#000000'),
                    'remark'   => array('value' => '
    感谢您的支持', 'color' => '#000000')
                );
                m('notice')->sendNotice(array('openid' => $openid, 'tag' => 'sns', 'default' => $message, 'cusdefault' => $text, 'datas' => $datas, 'plugin' => 'sns'));
            }

  • 人人商城异步操作菜单示例

     菜单:

    <a href='javascript:;' data-toggle='ajaxEdit' data-href="{php echo webUrl('goods/change',array('type'=>'displayorder','id'=>$item['id']))}" >{$item['displayorder']}</a>
    

    服务端方法
    public function change()
        {
            global $_W;
            global $_GPC;
            $id = intval($_GPC[‘id’]);

            if (empty($id)) {
                show_json(0, array('message' => '参数错误'));
            }
            else {
                pdo_update('ewei_shop_goods', array('newgoods' => 0), array('id' => $id));
            }

            $type = trim($_GPC[‘type’]);
            $value = trim($_GPC[‘value’]);

            if (!in_array($type, array('title', 'marketprice', 'total', 'goodssn', 'productsn', 'displayorder', 'dowpayment'))) {
                show_json(0, array('message' => '参数错误'));
            }

            $goods = pdo_fetch('select id,hasoption,marketprice,dowpayment,`type`,isdiscount,isdiscount_time from ' . tablename('ewei_shop_goods') . ' where id=:id and uniacid=:uniacid limit 1', array(':uniacid' => $_W[‘uniacid’], ':id' => $id));

            if (empty($goods)) {
                show_json(0, array('message' => '参数错误'));
            }

            if ($type == 'dowpayment') {
                if ($goods[‘marketprice’] < $value) {
                    show_json(0, array('message' => '定金不能大于总价'));
                }
            }
            else {
                if ($type == 'marketprice') {
                    if ($value < $goods[‘dowpayment’]) {
                        show_json(0, array('message' => '总价不能小于定金'));
                    }
                }
            }

            if ($type == 'total' && $goods[‘type’] == 3) {
                show_json(0, array('message' => '虚拟卡密产品不可直接修改库存'));
            }

            $result = pdo_update('ewei_shop_goods', array($type => $value), array('id' => $id));
            if ($type == 'total' && $result) {
                plog('goods.list', '编辑商品 ID: ' . $id . '<br>库存量为' . $value);
            }

            if ($goods[‘hasoption’] == 0 && !in_array($type, array('displayorder', 'total'))) {
                if ($goods[‘isdiscount’] == 0 || $goods[‘isdiscount_time’] < time()) {
                    $sql = 'update ' . tablename('ewei_shop_goods') . (' set minprice = marketprice,maxprice = marketprice where id = ' . $goods[‘id’] . ' and hasoption=0;');
                    pdo_query($sql);
                }
                else {
                    $sqlgoods = 'SELECT id,title,thumb,marketprice,productprice,minprice,maxprice,isdiscount,isdiscount_time,isdiscount_discounts,sales,total,description,merchsale FROM ' . tablename('ewei_shop_goods') . ' where id=:id and uniacid=:uniacid limit 1';
                    $goodsinfo = pdo_fetch($sqlgoods, array(':id' => $id, ':uniacid' => $_W[‘uniacid’]));
                    $goodsinfo = m('goods')->getOneMinPrice($goodsinfo);
                    pdo_update('ewei_shop_goods', array('minprice' => $goodsinfo[‘minprice’], ‘maxprice’ => $goodsinfo[‘maxprice’]), array(‘id’ => $id, ‘uniacid’ => $_W[‘uniacid’]));
                }
            }

            show_json(1);
        }

     

  • 微赞微擎中函数调用及获取系统和插件配置信息

    系统model中类的调用

    获取系统配置信息

    单个配置模块信息

    $shopset = m('common')->getSysset('trade');

    多个配置模块信息

    $shopset = m('common')->getSysset(array('shop', 'wap'));

    获取插件配置信息

    $snsSet = m("common")->getPluginset("sns");//sns配置信息

    调用函数获取用户信息

    $member = m('member')->getMember($openid);

    全局变量引用

    global $_W;
    global $_GPC;
    global $_S;

    推送 消息(公众号内)
     $msg = array(
        'keyword1' => array('value' => '荣获头衔通知', 'color' => '#73a68d'),
        'keyword2' => array('value' => '恭喜您荣获‘'.$honor_record[‘title’].'’头衔', 'color' => '#73a68d')
     );
    m('message')->sendCustomNotice($openid, $msg);

    调用文件内函数

    $this->zk_sort_array_multi($pageDate, [‘displayorder’], [‘desc’]);

     

  • 简单几句码实现PHP中对二维数组的排序

    PHP中对二维数组的排序

    方法一:


    /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys   要排序的键字段
     * @param string $sort  排序类型  SORT_ASC     SORT_DESC 
     * @return array 排序后的数组
     */
    function arraySort($array, $keys, $sort = SORT_ASC) {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }

    方法二:

       /*
         * 二维数组排序
         * */
        public function zk_sort_array_multi(array &$arr, array $keys, array $order)
        {
            //校验参数
            if ( count($keys) == ($times = count($order)) ) {
                for ( $i = 0, $j = 0; $j < $times; $i += 2, $j++ ) {
                    foreach ( $arr as $k => $v ) {
                        //原数组是否存在该字段
                        if ( isset($v[$keys[$j]]) ) {
                            $params[$i][] = $v[$keys[$j]];    //TODO 中文排序支持 //$params[$i][] = iconv(‘UTF-8’, ‘GBK’, $v[$keys[$j]]);
                        } else {
                            return false;
                        }
                    }
                    if ( strtoupper($order[$j]) == 'ASC' ) {
                        $params[$i + 1] = SORT_ASC;
                    } else {
                        $params[$i + 1] = SORT_DESC;
                    }
                }
                $params[] = &$arr;
                return call_user_func_array('array_multisort', $params);
            } else {
                return false;
            }
        }

  • 微赞微擎服务端SQL增删改查示例

    查询单条记录(一维)

            $sns_userInfo = pdo_fetch('select id,openid,honorid,honorids  from ' . tablename('ewei_shop_sns_member') . ' where uniacid=:uniacid and openid=:openid limit 1 ', array(':uniacid' => $_W[‘uniacid’], ':openid' => $openid));

    查询多条记录(二维)

                $list = pdo_fetchall('SELECT sr.*,ip.title,ip.desc,ip.thumb,ip.id ipid  FROM ' . tablename('ewei_shop_sns_study_record') . ' sr ' . ' left join ' . tablename('ewei_shop_ip_story') . ' ip on sr.fromid = ip.id ' .  (' WHERE 1 ' . $condition . '  ORDER BY sr.updatetime DESC limit ') . $begin . ',' . $psize2, $params);

    返回查询结果值

                $total = pdo_fetchcolumn('SELECT count(1) FROM ' . tablename('ewei_shop_sns_study_record') . (' WHERE 1 ' . $conditiontotal), $params);

                $ordermoney = pdo_fetchcolumn('select sum(price) from ' . tablename('ewei_shop_order') . ' where uniacid=:uniacid and openid=:openid and status=3 limit 1', array(':uniacid' => $_W[‘uniacid’], ‘:openid’ => $member[‘openid’]));

    新增记录

                $data = array();
                $data[‘credits’] = $credit;
                $data[‘openid’] = $openid;
                $data[‘uniacid’] = $_W[‘uniacid’];
                $data[‘signinday’] = $signinday;
                $data[‘credits_sum’] = $credits_sum;
                $data[‘signintime’] = $daynow;
                $data[‘totalday’] = $totalday;
                pdo_insert('ewei_shop_sns_sign_in', $data);
                $resid = pdo_insertid(); //返回新插入记录的id

    更新记录

            $newcredit = $sns_member[‘credit’] + $credit;

            if ($newcredit <= 0) {
                $newcredit = 0;
            }
            pdo_update('ewei_shop_sns_member', array('credit' => $newcredit), array('id' => $sns_member[‘id’]));

    删除记录

    直接执行sql语句

                pdo_query('delete from ' . tablename('ewei_shop_goods_spec_item') . (' where uniacid=' . $_W[‘uniacid’] . ' and specid=' . $spec_id . ' and id not in (') . implode(',', $itemids) . ')');

                pdo_delete('ewei_shop_goods', array('id' => $item[‘id’]));