php常用操作方法封装(文件处理、数据处理),复制即用

PHP常用操作封装:文件处理与数据处理技巧
本文介绍了PHP中的一些实用操作方法,包括获取日期范围、毫秒时间戳转换、对象生成、字符串数字排序、HTTP请求、驼峰命名、时间戳处理、首字母获取、二维码生成、文件压缩、下载、保存、更新和删除,以及数据处理等常见任务的实现。这些方法方便快捷,可直接应用于项目中。

获取日期范围内的日期


    /**
     * @description: 获取一个日期范围内的日期
     * @author Quan
     * @param {interval:日期范围,type:取值类型,-:获取之前日期;+:获取之后的日期} 
     * @return: 
     */
    protected function getDateInterval(int $interval, string $type): array
    {
        $dateArr = [];
        for ($i = $interval - 1; $i >= 0; $i--) {
            array_push($dateArr, date('Y-m-d', strtotime("{$type}{$i} day")));
        }
        if ($type == '+') $dateArr = array_reverse($dateArr);
        return $dateArr;
    }

毫秒时间戳

    /**
     * @description: 获取毫秒时间戳
     * @Author: Quan
     * @param {*}
     * @return {*}
     */   
    public static function millisecond(): float
    {
        [$usec, $sec] = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($usec) + floatval($sec)) * 1000);
    }

生成对象(对象含数组字符串形式和数组形式) 

   /**
     * @description: 生成对象(对象含数组字符串形式和数组形式)
     * @Author: Quan
     * @param {array}$arr
     * @return object{arr,arrStr}
     */
    static public function arrTranObj(array $arr): object
    {
        $obj = new stdClass;
        $obj->arr = $arr;
        $obj->arrStr = implode(',', $obj->arr);
        return $obj;
    }

字符串数字排序处理

字段后+0    可以将MySQL字符串字段按数值排序    注意:orderByRaw是laravel的原生排序方法

    /**
     * @description: 字符串数字排序处理
     * @Author: Quan
     * @param {*}
     * @return {*}
     */
    public static function orderByBlock(object $sql, string $sortBy, string $sortOrder, array $numberStr = []): object
    {
        if (in_array($sortBy, $numberStr)) {
            $sortBy = $sortBy . '+0';  //数字字符串排序处理
            return $sql->orderByRaw("$sortBy $sortOrder");
        }else{
            return $sql->orderBy($sortBy,$sortOrder);
        }
    }

发请求 

    /**
     * @description: 发请求
     * @Author: Quan
     * @param {*}
     * @return {*}
     */
    protected function requestSend(string $method = 'GET', string $url, array $params, array $header = []): array
    {
        $requestBody = http_build_query($params);

        $contentLen = mb_strlen($requestBody);
        $headerStr = "Content-Length: {$contentLen}\r\n";
        if (count($header) > 0) {
            foreach ($header as $k => $v) {
                $headerStr .= "{$k}: {$v}\r\n";
            }
        }
        $http = [
            'method' => $method,
            'header' => $headerStr,
            'content' => $requestBody
        ];
        $context = stream_context_create([
            'http' => $http
        ]);

        $response = file_get_contents($url, false, $context);
        $resArr = json_decode($response, true);
        if ($resArr['code'] !== 200) {
            throw new Exception($resArr['msg'], $resArr['code']);
        }
        return $resArr;
    }

驼峰字符串

    /**
     * @description: 驼峰命名转下划线命名
     * @param {type} 
     * @return {type} 
     */
    public  function uncamelize(string $camelCaps, string $separator = '_'): string
    {
        return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
    }
    /**
     * 下划线转驼峰
     * 思路:
     * step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
     * step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
     * @param $uncamelized_words
     * @param string $separator
     * @return string
     */
    protected function camelize(string $uncamelized_words, string $separator = '_'): string
    {
        $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
        return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
    }

时间戳处理 


    /**
     * @description: 人性化时间戳转换
     * @Author: Quan
     * @param {int} $time
     * @return string
     */
    public  function timeTran(int $time): string
    {
        $t = time() - $time;
        if ($t <= 0) {
            return  '刚刚';  //时间间隔小于1秒情况
        }
        $f = [
            '31536000' => '年',
            '2592000' => '个月',
            '604800' => '星期',
            '86400' => '天',
            '3600' => '小时',
            '60' => '分钟',
            '1' => '秒',
        ];

        foreach ($f as $k => $v) {
            if (0 != $c = floor($t / (int)$k)) {
                return $c . $v . '前';
            }
        }
    }

获取字符串首字母

  /**
     * 获取首字母
     * @param  string $str 汉字字符串
     * @return string 首字母
     */
    public function getInitials(string $str): string
    {
        $resStr = '#';
        if (empty($str)) {
            $resStr = '';
        }
        $firstLetter = substr($str, 0, 1);
        $fchar = ord($firstLetter);
        if ($fchar >= ord('A') && $fchar <= ord('z')) {
            $resStr = strtoupper($firstLetter);
        }
        $s1  = iconv('UTF-8', 'GBK//IGNORE', $str);
        $s2  = iconv('GBK//IGNORE', 'UTF-8', $s1);
        $s   = $s2 == $str ? $s1 : $str;
        $asc = ord(substr($s, 0, 1)) * 256 + ord(substr($s, 1, 1)) - 65536;
        if ($asc >= -20319 and $asc <= -20284) {
            $resStr = "A";
        }

        if ($asc >= -20283 and $asc <= -19776) {
            $resStr = "B";
        }

        if ($asc >= -19775 and $asc <= -19219) {
            $resStr = "C";
        }

        if ($asc >= -19218 and $asc <= -18711) {
            $resStr = "D";
        }

        if ($asc >= -18710 and $asc <= -18527) {
            $resStr = "E";
        }

        if ($asc >= -18526 and $asc <= -18240) {
            $resStr = "F";
        }

        if ($asc >= -18239 and $asc <= -17923) {
            $resStr = "G";
        }

        if ($asc >= -17922 and $asc <= -17418) {
            $resStr = "H";
        }

        if ($asc >= -17922 and $asc <= -17418) {
            $resStr = "I";
        }

        if ($asc >= -17417 and $asc <= -16475) {
            $resStr = "J";
        }

        if ($asc >= -16474 and $asc <= -16213) {
            $resStr = "K";
        }

        if ($asc >= -16212 and $asc <= -15641) {
            $resStr = "L";
        }

        if ($asc >= -15640 and $asc <= -15166) {
            $resStr = "M";
        }

        if ($asc >= -15165 and $asc <= -14923) {
            $resStr = "N";
        }

        if ($asc >= -14922 and $asc <= -14915) {
            $resStr = "O";
        }

        if ($asc >= -14914 and $asc <= -14631) {
            $resStr = "P";
        }

        if ($asc >= -14630 and $asc <= -14150) {
            $resStr = "Q";
        }

        if ($asc >= -14149 and $asc <= -14091) {
            $resStr = "R";
        }

        if ($asc >= -14090 and $asc <= -13319) {
            $resStr = "S";
        }

        if ($asc >= -13318 and $asc <= -12839) {
            $resStr = "T";
        }

        if ($asc >= -12838 and $asc <= -12557) {
            $resStr = "W";
        }

        if ($asc >= -12556 and $asc <= -11848) {
            $resStr = "X";
        }

        if ($asc >= -11847 and $asc <= -11056) {
            $resStr = "Y";
        }

        if ($asc >= -11055 and $asc <= -10247) {
            $resStr = "Z";
        }
        return $resStr;
    }

二维码

    /**
     * @description:生成二维码   需安装扩展simplesoftwareio/simple-qrcode 和 use SimpleSoftwareIO\QrCode\Facades\QrCode
     * @Author: Quan
     * @param {type} 
     * @return: 
     */
    public function qrcodeGenerateBase64(string $content): string
    {
        if (empty($content)) {
            throw new Exception('请传入二维码内容');
        }
        $orcode = base64_encode(QrCode::format('png')->margin(2)->size(200)->generate($content));
        // 输出
        $base64 = 'data:image/png;base64,' . $orcode;
        return $base64;
    }

文件压缩

    /**
     * @description:创建压缩文件,使用前需要use ZipArchive;
     * @Author: Quan
     * @param {type} 
     * @return: 
     */
    protected function zipCreate(array $filePaths, string $zipPath): void
    {
        $zip = new ZipArchive;
        $zip->open($zipPath, ZipArchive::CREATE);
        foreach ($filePaths as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
    }

文件下载 

/**
     * @description:文件下载,下载完自动删除,配合前端文件流下载 
     * @Author: Quan
     * @param {type} 
     * @return: 
     */
    protected function fileDownload(string $filePath): void
    {
        $fp = fopen($filePath, "r");
        $file_size = filesize($filePath);
        $buffer = 1024;  //设置一次读取的字节数,每读取一次,就输出数据(即返回给浏览器)
        $file_count = 0; //读取的总字节数
        //向浏览器返回数据 
        while (!feof($fp) && $file_count < $file_size) {
            $file_con = fread($fp, $buffer);
            $file_count += $buffer;
            echo $file_con;
        }
        fclose($fp);
        //下载完成后删除文件
        if ($file_count >= $file_size) {
            unlink($filePath);
        }
    }

文件保存

   /**
     * @description: 保存文件
     * @Author: Quan
     * @param {type} 
     * @return {type} 
     */
    protected  function saveFile(string $fileName = '', string $content = '', int  $mode = 0777): string
    {
        $filePath = dirname($fileName);
        if (!file_exists($filePath)) {
            mkdir($filePath, $mode, true);
        }
        $fp = fopen($fileName, "w");
        fwrite($fp, $content);
        fclose($fp);
        return $fileName;
    }


   /**
     * @description: 第三方图片转换本地
     * @Author: Quan
     * @param {type} 
     * @return string
     */
    protected function thridFileSave(string $url): string
    {
        $fileContent = file_get_contents($url);
        $fileName = $this->getFileName('jpg', 'avatar');
        $basePath = '/uploads/user/avatar/' . date("Ymd", time()) . '/' . $fileName;
       //$resPath = public_path($basePath); //laravel 框架中需要加这行 
        $resPath = $basePath;
        $this->saveFile($resPath, $fileContent);
        return $basePath;
    }

文件更新 

   /**
     * @description:文件更新,新文件内容更新到原文件中,并删除新文件 
     * @Author: Quan
     * @param {type} 
     * @return: 
     */
    protected function fileUpdate(string $newPath, string $oldPath): void
    {
        $path = $newPath;
        $oldPath = $oldPath;
        if (file_exists($path) && $path !== $oldPath && $newPath) {
            $content = file_get_contents($path);
            file_put_contents($oldPath, $content);
            unlink($path);
        }
    }

文件删除相关

 /**
     * @description:批量删除文件 
     * @Author: Quan
     * @param {type} 
     * @return: 
     */
    protected function deleteBatchFile(array  $paths): void
    {
        array_map(function ($path) {     
                $path = $path;
            file_exists($path) && is_file($path) && unlink($path);
        }, $paths);
    }
    /**
     * @description:删除单个文件 
     * @Author: Quan
     * @param {type} 
     * @return: 
     */
    protected function deleteFile(string   $path): void
    {
        file_exists($path) && is_file($path) && unlink($path);
    }

数据处理相关

    /**
     * treeData 生成树状数据
     * @author Quan
     * @param  array $items  原数据
     * @param  string $son 存放孩子节点字段名
     * @param  string $id 排序显示的键,一般是主键 
     * @param  array  $pid  父id
     * @return array  树状数据
     */
    protected function treeData(array $items = [], string  $pid = 'parent_id', string $id = 'id', string  $son = 'children'): array
    {
        $tree = [];
        $tmpData = []; //临时数据
        foreach ($items as $item) {
            $tmpData[$item[$id]] = $item;
        }
        foreach ($items as $item) {
            if (isset($tmpData[$item[$pid]])) {
                $tmpData[$item[$pid]][$son][] = &$tmpData[$item[$id]];
            } else {
                $tree[] = &$tmpData[$item[$id]];
            }
        }
        unset($tmpData);
        return $tree;
    }   
 /**
     * @description:过滤数组为null和''的字段,array_filter也能过滤,但其默认会把0、false这样具体的值过滤掉
     * @Author: Quan
     * @param  array  $arr
     * @return array
     */
    static protected function filterArray(array $arr): array
    {
        foreach ($arr as $k => $v) {
            if ($v === '' || $v === null) {
                unset($arr[$k]);
            }
        }
        return $arr;
    }   
 /**
     * @description: 10进制转36进制
     * @Author: Quan
     * @param {type} 
     * @return: 
     */
    protected function createCode(string $number): string
    {
        static $sourceString = [
            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
            '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'
        ];

        $num = $number;
        $code = '';
        while ($num) {
            $mod = bcmod($num, '36');
            $num = bcdiv($num, '36');
            $code = "{$sourceString[$mod]}{$code}"; //邀请码拼接
        }
        //判断code的长度
        if (empty($code[4]))
            $code = str_pad($code, 5, '0', STR_PAD_LEFT); //长度不够拼接'0'

        return $code;
    }
    /**
     * @description: 删除html和空格
     * @Author: Quan
     * @param {type} 
     * @return: 
     */
    public function htmlTagFilter(?string $str): string
    {
        $resStr = '';
        if (!empty($str)) {
            $tmpStr = strip_tags($str);
            $resStr = str_replace(array("&nbsp;", "&ensp;", "&emsp;", "&thinsp;", "&zwnj;", "&zwj;", "&ldquo;", "&rdquo;"), "", $tmpStr);
        }
        return $resStr;
    }
    /**
     * @description: 字符串截取
     * @Author: Quan
     * @param {type} 
     * @return: 
     */
    public function strCut(?string $str, int $startIndex, int $length, string $prefix = '...'): string
    {
        $resStr = '';
        if (!empty($str)) {
            $resStr = mb_strlen($str) > $length ? mb_substr($str, $startIndex, $length) . $prefix : $str;
        }
        return $resStr;
    }
    /**
     * @description: xml 转换数组
     * @Author: Quan
     * @param {type} 
     * @return: 
     */
    public function xmlToArray(string $xml): array
    {

        libxml_disable_entity_loader(true);
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $arr;
    }
    /**
     * @description: 号码打码
     * @Author: Quan
     * @param {type} 
     * @return: 
     */
    public function mobileMosaicStr(string $mobile): string
    {
        return  substr($mobile, 0, 3) . '****' . substr($mobile, 7);
    }
    /**
     * 数组转对象
     * @param Array $array
     * @author Quan
     * @return Object
     */
    protected function arrayTransitionObject(array $array): object
    {
        if (is_array($array)) {
            $obj = new stdClass();
            foreach ($array as $key => $val) {
                $obj->$key = $val;
            }
        } else {
            $obj = $array;
        }
        return $obj;
    }
    /**
     * @description: 分析枚举类型配置值 格式 a:名称1,b:名称2
     * @param {str:string} 
     * @return: 
     */
    protected function parseValue(string $str): array
    {
        $tmp = preg_split('/[,;\r\n]+/', $str);
        $value = [];
        if (strpos($str, ':')) {
            foreach ($tmp as $val) {
                list($k, $v) = explode(':', $val);
                $value[$k] = $v;
            }
        } else {
            $value = $tmp;
        }
        return $value;
    }
    /**
     * @description:数据分组 
     * @param {dataArr:需要分组的数据;keyStr:分组依据} 
     * @author Quan
     * @return: 
     */
    static protected function dataGroup(array $dataArr, string $keyStr): array
    {
        $newArr = [];
        foreach ($dataArr as $k => $val) {   
            $newArr[$val[$keyStr]][] = $val;
        }
        return $newArr;
    }

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值