您的位置 首页 php

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

字符串数字排序处理

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

     /**
     * @description: 字符串数字排序处理
     * @Author: Quan
     * @param {*}
     * @return {*}
     */    public  static  function orderByBlock(object $sql, string $sortBy, string $sortOrder, array $ number Str = []): 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  request Send(string $method = 'GET', string $url, array $ params , array $header = []): array
    {
        $requestBody = http_build_query($params);

        $contentLen = mb_strlen($requestBody);
        $ header Str = "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', 'gb2312', $str);
        $s2  = iconv('gb2312', '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  Zip Archive;
     * @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($ file Name, "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 delete Batch File(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(" ", " ", " ", " ", "‌", "‍", "“", "”"), "", $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;
    }  

文章来源:智云一二三科技

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

文章地址:https://www.zhihuclub.com/79318.shtml

关于作者: 智云科技

热门文章

网站地图