这是对于tp的学习笔记及分享,会一直更新,保持学习的进步
tp5 tp6 index方法 if (Request ::isPost ()) { $keys = $this ->request->post ('keys' , '' , 'trim' ); $where = []; if ($keys != '' ) { $where [] = ['title' , 'like' , '%' . $keys . '%' ]; } $page = $this ->request->post ('page' ); $limit = $this ->request->post ('limit' ); $tol = ($page - 1 ) * $limit ; $banner = BannerModel ::where ($where )->limit ($tol , $limit )->select (); $count = BannerModel ::where ($where )->count (); if (!$banner ) error (); success ($banner , $count ); } return view ();
封装上传方法
一、打开项目在config文件夹下创建upload.php配置文件用来管理文件上传的后缀和大小
<?php return [ 'suffix_arr' => [ 'image' => 'jpg,jpeg,png,gif' , 'file' => 'zip,gz,doc,txt,pdf,xls' , ], 'size_arr' => [ 'image' => 10 , 'file' => 50 ], ];
二、修改config\filesystem.php配置文件配置上传根目录及上传规则
<?php return [ 'default' => 'local' , 'disks' => [ 'local' => [ 'type' => 'local' , 'root' => app ()->getRuntimePath () . 'storage' , ], 'public' => [ 'type' => 'local' , 'root' => app ()->getRootPath () . 'public/storage' , 'url' => '/storage' , 'visibility' => 'public' , ], 'excel' => [ 'type' => 'local' , 'root' => app ()->getRootPath () . 'public' , 'url' => '/excel' , 'visibility' => 'public' , ], ], ];
在app\controller目录下创建Upload.php类并编写upload()文件上传方法,如果是这样加个post请求判断
放在common方法里的话,可以直接调用
public function upload ($file , $name = 'file' , $type = 'file' ) { $upload_dir = '/' . $type . '/' . $name ; try { $suffix_config = config ('upload.suffix_arr' ); $size_config = config ('upload.size_arr' ); if (empty ($size_config [$type ]) || empty ($size_config [$type ])) { return false ; } else { $suffix = $suffix_config [$type ]; $size = $size_config [$type ]; } validate (['file' => [ //限制文件大小 'fileSize' => $size * 1024 * 1024 , //限制文件后缀 'fileExt' => $suffix ]], [ 'file.fileSize' => '上传的文件大小不能超过' . $size . 'M' , 'file.fileExt' => '请上传后缀为:' . $suffix . '的文件' ])->check (['file' => $file ]); $filename = \think\facade\Filesystem ::disk ('public' )->putFile ($upload_dir , $file ); if ($filename ) { $src = '/storage/' . $filename ; return $src ; } else { return json (['code' => 0 , 'msg' => '上传失败' ]); } } catch (ValidateException $e ) { return json (['code' => 0 , 'msg' => $e ->getMessage ()]); } }
浏览器下载文件 public function head_upload ($file_name ) { $file_name = iconv ("utf-8" , "gbk//IGNORE" , $file_name );; $file_dir = $_SERVER ['DOCUMENT_ROOT' ]."/excel_template/" ; if (!file_exists ($file_dir . $file_name )) { header ('HTTP/1.1 404 NOT FOUND' ); } else { $file = fopen ($file_dir . $file_name , "rb" ); Header ("Content-type: application/octet-stream" ); Header ("Accept-Ranges: bytes" ); Header ("Accept-Length: " . filesize ($file_dir . $file_name )); Header ("Content-Disposition: attachment; filename=" . $file_name ); echo fread ($file , filesize ($file_dir . $file_name )); fclose ($file ); exit (); } }
tp 时间操作 php字符串类型时间转为秒数 $len = "00:05:10.11" ; $time = date_parse ($len ); $seconds = $time ['hour' ] * 3600 + $time ['minute' ] * 60 + $time ['second' ];
判断两天是否是同一天 function isDiffDays ($last_date , $this_date ) { if (($last_date ['year' ] === $this_date ['year' ]) && ($this_date ['yday' ] === $last_date ['yday' ])) { return true ; } else { return false ; }
传入时间计算距离现在第几周
未区分星期一,直接计算
public function current_week ($time_chuo_of_first_day = '' ) { $month = date ('n' ); $day = date ('d' ); $year = date ('Y' ); $time_chuo_of_current_day = mktime (0 , 0 , 0 , $month , $day , $year ); $cha = ($time_chuo_of_current_day - $time_chuo_of_first_day ) / 60 / 60 / 24 ; $zhou = (int )(($cha +1 ) / 7 + 1 ); return $zhou ; }
传入周,计算周一的日期
public function mon ($date ) { $now = strtotime ($date ); $number = date ("w" ,$now ); $number = $number == 0 ? 7 : $number ; $diff_day = $number - 1 ; return date ("Y-m-d" ,$now - ($diff_day * 60 * 60 * 24 )); }
数据库操作——查询 tp5查询用逗号分开的字段 $log_article = LogArticle ::where ('find_in_set(:id,tag_ids)' ,['id' => input ('tag_id' )]) ->select ();
页数 $tol = ($page -1 ) *$limit ;
关键字搜索 if ($keys != '' ) { $where [] = ['title' ,'like' ,'%' .$keys .'%' ]; }
数据库操作——插入 分组插入数据库
insert_data是需要插入的数据
$num = 100 ;$limit = ceil (count ($insert_data )/$num );for ($i = 1 ; $i <= $limit ; $i ++){ $offset = ($i -1 )*$num ; $data = array_slice ($insert_data , $offset , $num ); }
数据库其它操作 事务 Db ::startTrans ();try { Db ::table ('think_user' )->find (1 ); Db ::table ('think_user' )->delete (1 ); throw new Exception ('添加商品规格失败' , 1 ); Db ::commit (); } catch (\Exception $e ) { $code = $e ->getCode (); if ($code == 0 ){ retMsg (0 , $e ->getMessage ()); }else { retMsg (0 , '网络繁忙,请稍后再试~' ,['error' => $e ->getMessage ()]); } Db ::rollback (); }
模型 模型中无限分类
这是lemocms中的,但是都通用,传入的$cate需要分类的数组
public static function cateTree ($cate , $lefthtml = '|— ' , $pid = 0 , $level = 0 ) { $arr = array (); foreach ($cate as $v ){ if ($v ['pid' ] == $pid ) { $v ['level' ] = $level + 1 ; $v ['lefthtml' ] = str_repeat ($lefthtml ,$level ); $v ['ltitle' ] = $v ['lefthtml' ].$v ['title' ]; $arr [] = $v ; $arr = array_merge ($arr , self ::cateTree ($cate , $lefthtml , $v ['id' ], $level +1 )); } } return $arr ; }
Base函数 index基础函数
可以仿照为base,其他根据需求更改
public function index ( ) { if (Request ::isPost ()) { $keys = $this ->request->post ('keys' , '' , 'trim' ); $where = []; if ($keys != '' ) { $where [] = ['title' , 'like' , '%' . $keys . '%' ]; } $page = $this ->request->post ('page' ); $limit = $this ->request->post ('limit' ); $tol = ($page - 1 ) * $limit ; $banner = BannerModel ::where ($where )->limit ($tol , $limit )->select (); $count = BannerModel ::where ($where )->count (); if (!$banner ) $this ->errorMsg (); $this ->successMsg ($banner , $count ); } return view (); }
配置伪静态 apache配置
从官网下载的index.php后面没有 ?
因此这个和官网的区别在于index.php后面的 ?
<IfModule mod_rewrite.c> Options +FollowSymlinks -Multiviews RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php?/$1 [QSA,PT,L] </IfModule>
设置目录浏览 在conf下找到vhosts.conf文件或者vhosts目录里,localhost配置下Options一行加上indexes即
Nginx配置 if (!-d $request_filename ){ set $rule_0 1 $rule_0 ; } if (!-f $request_filename ){ set $rule_0 2 $rule_0 ; } if ($rule_0 = "21" ){ rewrite ^/(.*)$ /index.php?s=/$1 last; }
上传,导出,下载 上传excel,并且将其数据插入数据库
php上传excel需要用到PHPExcel
需要composer安装:composer require phpoffice/phpexcel(该方法最好实时从网上寻找,此不一定管用,以实际为准)
composer安装完成在方法中使用
use PHPExcel_IOFactory ;use PHPExcel ;
tp中使用
public function excel_upload ( ) { Db ::startTrans (); try { $file = $_FILES ['file' ]; $extension = strtolower (pathinfo ($file ['name' ], PATHINFO_EXTENSION)); if ($extension == "xlsx" ) { $objReader = \PHPExcel_IOFactory ::createReader ('Excel2007' ); } else { exit (json_encode (['status' => 0 , 'msg' => '不是期望的文件' ])); } $PHPExcel = $objReader ->load ($file ['tmp_name' ]); $currentSheet = $PHPExcel ->getSheet (0 ); $allColumn = $currentSheet ->getHighestColumn (); $allRow = $currentSheet ->getHighestRow (); for ($currentRow = 1 ; $currentRow <= $allRow ; $currentRow ++) { for ($currentColumn = 'A' ; $currentColumn <= $allColumn ; $currentColumn ++) { $address = $currentColumn . $currentRow ; $cell = $currentSheet ->getCell ($address )->getValue (); $data [$currentRow - 1 ][$currentColumn ] = $cell ; } } $objContent = $objReader ->load ($file ['tmp_name' ]); $sheetContent = $objContent ->getSheet (0 ) ->toArray (); $excel_array = $sheetContent [0 ]; array_shift ($sheetContent ); $data = []; foreach ($sheetContent as $k => $v ){ $data [$k ]['supplier_name' ] = $v [0 ]; $data [$k ]['goods_code' ] = $v [1 ]; $data [$k ]['goods_name' ] = $v [2 ]; $data [$k ]['color' ] = $v [3 ]; $data [$k ]['color_code' ] = $v [4 ]; $data [$k ]['size_code' ] = $v [5 ]; $data [$k ]['size_name' ] = $v [6 ]; $data [$k ]['barcode' ] = $v [7 ]; $data [$k ]['inventory' ] = $v [8 ]; if (count ($v ) > 9 ){ $shops_id = '' ; $num = '' ; for ($i = 1 ; $i <= count ($v )-9 ; $i ++){ if ($v [8 +$i ] != null ){ $shops = Shops ::where (['name' => $excel_array [8 +$i ]])->find (); if (!$shops ) throw new Exception ('没有该店铺' .$excel_array [8 +$i ].',请在后台添加' , 1 ); $shops_id = $shops ['id' ].',' .$shops_id ; $num = $v [8 +$i ].',' .$num ; } } $shops_ids = substr ($shops_id ,0 , strlen ($shops_id )-1 ); $nums = substr ($num ,0 , strlen ($num )-1 ); $data [$k ]['num' ] = $nums ; $data [$k ]['shop_id' ] = $shops_ids ; } } Db ::commit (); success (); } catch (Exception $e ) { Db ::rollback (); error ($e ->getMessage ()); } }
PHPExcel插入数据库内存溢出解决方案
方法1、扩大php默认分配内存
ini_set("memory_limit", "13312M"); set_time_limit(0);
导出为excel
$fileName = '表名',$headArr = ['关键词', '出现次数'](对应excel的表头);
$data = [ [ '数据1' , '数据 2' ], [ '数据1' , '数据2' ] ];
public function chu_ci_list ( ) { $fileName = '词云图统计表' ; $headArr = ['关键词' , '出现次数' ]; $ci_list = Cache ::get ('ci_list' ); $ci_data = unserialize ($ci_list ); $data = array (); $i = 0 ; foreach ($ci_data as $k => $item ){ $data [$i ][0 ] = $k ; $data [$i ][1 ] = $item ; $i ++; } $fileName .= "-" . date ("YmdHi" , time ()) . ".xlsx" ; $objPHPExcel = new \PHPExcel (); $objPHPExcel ->getProperties (); $key = ord ("A" ); foreach ($headArr as $v ) { $colum = chr ($key ); $objPHPExcel ->setActiveSheetIndex (0 )->setCellValue ($colum . '1' , $v ); $objPHPExcel ->setActiveSheetIndex (0 )->setCellValue ($colum . '1' , $v ); $key += 1 ; } $column = 2 ; $objActSheet = $objPHPExcel ->getActiveSheet (); foreach ($data as $key => $rows ) { $span = ord ("A" ); foreach ($rows as $keyName => $value ) { $objActSheet ->setCellValue (chr ($span ) . $column , $value ); $span ++; } $column ++; } $fileName = iconv ("utf-8" , "gb2312" , $fileName ); $objPHPExcel ->setActiveSheetIndex (0 ); header ('Content-Type: application/vnd.ms-excel' ); header ("Content-Disposition: attachment;filename=$fileName " ); header ('Cache-Control: max-age=0' ); $objWriter = \PHPExcel_IOFactory ::createWriter ($objPHPExcel , 'Excel5' ); $objWriter ->save ('php://output' ); exit (); }
字符串,数组操作 提取字符串中的数字 public function findNum ($str = '' ) { $str = trim ($str ); if (empty ($str )) { return '' ; } $result = '' ; for ($i = 0 ; $i < strlen ($str ); $i ++) { if (is_numeric ($str [$i ])) { $result .= $str [$i ]; } } return $result ; }
php实现数组按指定KEY排序的方法 public function array_sort ($arr ,$keys ,$orderby ='asc' ) { $keysvalue = $new_array = array (); foreach ($arr as $k =>$v ){ $keysvalue [$k ] = $v [$keys ]; } if ($orderby == 'asc' ){ asort ($keysvalue ); }else { arsort ($keysvalue ); } reset ($keysvalue ); foreach ($keysvalue as $k =>$v ){ $new_array [] = $arr [$k ]; } return $new_array ; }
打印日志 file_put_contents ('ss.txt' ,'data:-->' .'0' .PHP_EOL,FILE_APPEND);
php PHP采用超长(超大)数字运算防止数字以科学计数法显示的方法 function calc ($m ,$n ,$x ) { $errors =array ( '被除数不能为零' , '负数没有平方根' ); switch ($x ){ case 'add' : $t =bcadd ($m ,$n ); break ; case 'sub' : $t =bcsub ($m ,$n ); break ; case 'mul' : $t =bcmul ($m ,$n ); break ; case 'div' : if ($n !=0 ){ $t =bcdiv ($m ,$n ); }else { return $errors [0 ]; } break ; case 'pow' : $t =bcpow ($m ,$n ); break ; case 'mod' : if ($n !=0 ){ $t =bcmod ($m ,$n ); }else { return $errors [0 ]; } break ; case 'sqrt' : if ($m >=0 ){ $t =bcsqrt ($m ); }else { return $errors [1 ]; } break ; } $t =preg_replace ("/\..*0+$/" ,'' ,$t ); return $t ; }
截取后缀名 $postfix = trim (strrchr ($file_name , '.' ),'' );
将反斜杠转成正斜杠 $path = str_replace ("\\" ,'/' ,$info ->getSaveName ());
应用公共返回方法 function success ($data = [], $count = 0 ) { header ("Access-Control-Allow-Origin:*" ); header ('Access-Control-Allow-Methods:POST,GET' ); header ('Content-Type:application/json' ); $list ['code' ] = 1 ; $list ['msg' ] = '操作成功' ; $list ['data' ] = $data ; $list ['count' ] = $count ; echo json_encode ($list ); die ; } function error ($msg = 'error' ) { header ("Access-Control-Allow-Origin:*" ); header ('Access-Control-Allow-Methods:POST,GET' ); header ('Content-Type:application/json' ); $list ['code' ] = 0 ; $list ['msg' ] = $msg ; echo json_encode ($list ); die ; } function retMsg ($code = 0 ,$msg = '' , $data = [], $count = 0 ) { header ("Access-Control-Allow-Origin:*" ); header ('Access-Control-Allow-Methods:POST,GET' ); header ('Content-Type:application/json' ); $list ['code' ] = $code ; $list ['msg' ] = $msg ; $list ['data' ] = $data ; $list ['count' ] = $count ; echo json_encode ($list ); die ; }
封装概率 public function get_rand ($proArr ) { $result = array (); foreach ($proArr as $key => $val ) { $arr [$key ] = $val ['v' ]; } $proSum = array_sum ($arr ); asort ($arr ); foreach ($arr as $k => $v ) { $randNum = mt_rand (1 , $proSum ); if ($randNum <= $v ) { $result = $proArr [$k ]; break ; } else { $proSum -= $v ; } } return $result ; }