抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

这是对于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路径
'url' => '/storage',
// 可见性
'visibility' => 'public',
],
// 更多的磁盘配置信息
'excel' => [
// 磁盘类型
'type' => 'local',
// 磁盘路径
'root' => app()->getRootPath() . 'public',
// 磁盘路径对应的外部URL路径
'url' => '/excel',
// 可见性
'visibility' => 'public',
],
],
];

在app\controller目录下创建Upload.php类并编写upload()文件上传方法,如果是这样加个post请求判断

放在common方法里的话,可以直接调用

/**
* 上传方法
* @param $file
* @param string $name
* @param string $type
* @return bool|\think\response\Json
*
* User: mi
* Date: 2020-09-14
*/
public function upload($file, $name = 'file', $type = 'file')
{
//接收文件上传类型
// $type = request()->param('type', '', 'trim');
// $name = request()->param('name', '', 'trim');
//
// //获取表单上传文件
// $file = request()->file('file');

//组装文件保存目录
$upload_dir = '/' . $type . '/' . $name;

try {
//从config/upload.php配置文件中读取允许上传的文件后缀和大小
$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 json(['code' => 1, 'result' => $src]);
return $src;

} else {

return json(['code' => 0, 'msg' => '上传失败']);

}

} catch (ValidateException $e) {

return json(['code' => 0, 'msg' => $e->getMessage()]);

}

}

浏览器下载文件

/**
* 封装下载excel
* User: mi
* Date: 2020-10-12
*/
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");
//Content-Length是指定包含于请求或响应中数据的字节长度
Header("Accept-Length: " . filesize($file_dir . $file_name));
//用来告诉浏览器,文件是可以当做附件被下载,下载后的文件名称为$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'); //获取月 n
$day = date('d'); //获取日 d
$year = date('Y'); //获取年 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; //如遇周末,将0换成7
$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需要分类的数组

/**
* 无限分类-权限
* @param $cate 栏目
* @param string $lefthtml 分隔符
* @param int $pid 父ID
* @param int $lvl 层级
* @return array
*/
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即

image-20210329145321957

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中使用

// excel上传
public function excel_upload(){
Db::startTrans();
try {
$file = $_FILES['file']; //需要用这种方法接收
$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); //pathinfo()函数以数组的形式返回文件路径的信息

if ($extension == "xlsx") {
//2007(相当于是打开接收的这个excel)
$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
} else {
//2003(相当于是打开接收的这个excel)
exit(json_encode(['status' => 0, 'msg' => '不是期望的文件']));
}

// 这是另外一种,把表数据分为ABCD等来区分
//载入文件
$PHPExcel = $objReader->load($file['tmp_name']);

//获取表中的第一个工作表,如果要获取第二个,把0改为1,依次类推
$currentSheet = $PHPExcel->getSheet(0);
//获取总列数
$allColumn = $currentSheet->getHighestColumn();
//获取总行数
$allRow = $currentSheet->getHighestRow();

//循环获取表中的数据,$currentRow表示当前行,从哪行开始读取数据,索引值从0开始
for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
//从哪列开始,A表示第一列
for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
//数据坐标
$address = $currentColumn . $currentRow;
//读取到的数据,保存到数组$data中
$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'
]
];
/**
* 导出词云表
* User: mi
* Date: 2020-09-29
*/
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); // 设置活动单指数到第一个表,所以Excel打开这是第一个表

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排序的方法

// 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;
}

封装概率

/**
* 封装概率
* 作者:糜家智
* 时间:2021/4/29 17:19
*/
public function get_rand($proArr)
{
$result = array();
foreach ($proArr as $key => $val) {
$arr[$key] = $val['v']; // probability中奖概率
}
// 概率数组的总概率
$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;
}

评论