PHP常用方法

方法一: 将指定颜色变浅

    // 将指定颜色变浅
    public static function adjustBrightness($hex, $steps) {
        // Steps should be between -255 and 255. Negative = darker, positive = lighter
        $steps = max(-255, min(255, $steps));

        // Normalize into a six character long hex string
        $hex = str_replace('#', '', $hex);
        if (strlen($hex) == 3) {
            $hex = str_repeat(substr($hex,0,1), 2).str_repeat(substr($hex,1,1), 2).str_repeat(substr($hex,2,1), 2);
        }

        // Split into three parts: R, G and B
        $color_parts = str_split($hex, 2);
        $return = '#';

        foreach ($color_parts as $color) {
            $color   = hexdec($color); // Convert to decimal
            $color   = max(0,min(255,$color + $steps)); // Adjust color
            $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
        }

        return $return;
    }

方法二:数组转树形

    // 数组转树
    public static function list_to_tree($list, $root = 0, $pk = 'id', $pid = 'parentid', $child = '_child') {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] = &$list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = 0;
                if (isset($data[$pid])) {
                    $parentId = $data[$pid];
                }
                if ((string) $root == $parentId) {
                    $tree[] = &$list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent = &$refer[$parentId];
                        $parent[$child][] = &$list[$key];
                    }
                }
            }
        }
        return $tree;
    }

方法三:去除多维数组空值

   /**
     * 去除多维数组中的空值
     * @author
     * @return mixed
     * @param $arr 目标数组
     * @param array $values 去除的值  默认 去除  '',null,false,0,'0',[]
     */
    public static function filter_array($arr, $values = ['', null, false, 0, '0',[]]) {
        foreach ($arr as $k => $v) {
            if (is_array($v) && count($v)>0) {
                $arr[$k] = self::filter_array($v, $values);
            }
            foreach ($values as $value) {
                if ($v === $value) {
                    unset($arr[$k]);
                    break;
                }
            }
        }
        return $arr;
    }

方法四:PHP数组分页

  /*
    * 数组分页
    * $arr         php 数组
    * $rowsPerPage 每页显示的数量
    * $url         页面地址
    * $curPage     当前页
    * return       $ret 结果数组,直接放在前端循环输出; $pageNumString 处理的分页,直接放在前端使用
    * ![在这里插入图片描述](https://img-blog.csdnimg.cn/20201026140440860.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3hpYW95YW55YW5saA==,size_16,color_FFFFFF,t_70#pic_center)

    */
    public static function arrayPage($arr, $rowsPerPage, $url, $curPage = 1, $param = 'curpage')
    {
        // 数组总数
        $totalPage = count($arr);

        // 首页
        $begin     = ($curPage - 1) * $rowsPerPage;

        // 每页显示的记录
        $ret       = array_slice($arr, $begin, $rowsPerPage);

        // 总页数
        $totalPage = ceil($totalPage / $rowsPerPage);

        // 存储页面字符串
        $pageNumString = '';

        if ($curPage <= 5) {
            $begin = 1;
            $end = $totalPage >= 10 ? 10 : $totalPage;
        } else {
            $end = $curPage + 5 > $totalPage ? $totalPage : $curPage + 5;
            $begin = $end - 9 <= 1 ? 1 : $end - 9;
        }

        // 上一页
        $prev = $curPage - 1 <= 1 ? 1: $curPage - 1;
        $pageNumString .= "<li><a href='$url?$param=1'>首页</a></li>";
        $pageNumString .= "<li><a href='$url?$param=$prev'>&laquo;</a></li>";

        //根据起始页与终止页将当前页面的页码显示出来
        for ($i = $begin; $i <= $end;$i ++) {
            //使用if实现高亮显示当前点击的页码
            //这是 bootstrap的全局样式
            if ($curPage == $i) {
                $pageNumString .= "<li class='active'><a href='$url?$param=$i'>$i</a></li>";
            } else {
                $pageNumString .= "<li><a href='$url?$param=$i'>$i</a></li>";
            }
        }

        //实现下一页
        $next = $curPage + 1 >= $totalPage ? $totalPage : $curPage + 1;
        $pageNumString .= "<li><a href='$url?$param=$next'>&raquo;</a></li>";
        $pageNumString .= "<li><a href='$url?$param=$totalPage'>尾页</a></li>";

        return ['ret' => $ret, 'pageNumString' => $pageNumString];
    }

方法五:将Base64图片转换为本地图片并保存

 /**
     * [将Base64图片转换为本地图片并保存]
     * @E-mial 123@163.com
     * @TIME   2017-04-07
     * @WEB    http://www.baidu.com
     * @param  [Base64] $base64_image_content [要保存的Base64]
     * @param  [目录] $path [要保存的路径]
     */
    
    public static function base64_image_content($base64_image_content,$path) 
    {

        // 匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            // $type = $result[2];
            $type = "jpg";
            $new_file1 = $path . date('Ymd') . DS;
             
            if (!file_exists($new_file1)) {
                
                //检查是否有该文件夹,如果没有就创建,并给予最高权限
                mkdir($new_file1, 0755, true);
            }

            // 原图路径
            $new_file = $new_file1 . time() . ".{$type}";

            // 缩略图路径
            $dist_img = $new_file1 . time() . "_yasuo.{$type}";
            
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {

                // 压缩图片
                $dist = self::img2thumb($new_file, $dist_img, 150, 150, 0, 0.4);
                if ($dist) {
                    return ["src_img" => $new_file, "dist_img" => $dist_img];
                } else {
                    return false;
                }
                
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

     /**
     * 生成缩略图
     *
     * @param string $src_img    源图绝对完整地址{带文件名及后缀名}
     * @param string $dst_img    目标图绝对完整地址{带文件名及后缀名}
     * @param int    $width      缩略图宽{0:此时目标高度不能为0,目标宽度为源图宽*(目标高度/源图高)}
     * @param int    $height     缩略图高{0:此时目标宽度不能为0,目标高度为源图高*(目标宽度/源图宽)}
     * @param int    $cut        是否裁切{宽,高必须非0}
     * @param int    $proportion 缩放{0:不缩放, 0<this<1:缩放到相应比例(此时宽高限制和裁切均失效)}
     *
     * @return boolean
     */
    public static function img2thumb($src_img, $dst_img, $width = 75, $height = 75, $cut = 0, $proportion = 0)
    {
        if (! is_file($src_img) || filesize($src_img) <= 0) {
            return false;
        }

        $ot     = pathinfo($dst_img, PATHINFO_EXTENSION);
        $otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot);
        if (! function_exists($otfunc)) {
            Log::error("undefined function: {$otfunc}", func_get_args());
            return false;
        }

        $srcinfo   = @getimagesize($src_img);
        $src_w     = $srcinfo[0];
        $src_h     = $srcinfo[1];
        $type      = strtolower(substr(image_type_to_extension($srcinfo[2]), 1));
        $createfun = 'imagecreatefrom' . ($type == 'jpg' ? 'jpeg' : $type);
        $dst_h     = $height;
        $dst_w     = $width;
        $x         = $y = 0;

        if (! function_exists($createfun)) {
            Log::error("undefined function: {$createfun}", func_get_args());
            return false;
        }

        /**
         * 缩略图不超过源图尺寸(前提是宽或高只有一个)
         */
        if (($width > $src_w && $height > $src_h) || ($height > $src_h && $width == 0) || ($width > $src_w && $height == 0)) {
            $proportion = 1;
        }
        if ($width > $src_w) {
            $dst_w = $width = $src_w;
        }
        if ($height > $src_h) {
            $dst_h = $height = $src_h;
        }
        if (! $width && ! $height && ! $proportion) {
            return false;
        }
        if (! $proportion) {
            if ($cut == 0) {
                if ($dst_w && $dst_h) {
                    if ($dst_w / $src_w > $dst_h / $src_h) {
                        $dst_w = $src_w * ($dst_h / $src_h);
                        $x     = 0 - ($dst_w - $width) / 2;
                    } else {
                        $dst_h = $src_h * ($dst_w / $src_w);
                        $y     = 0 - ($dst_h - $height) / 2;
                    }
                } else {
                    if ($dst_w xor $dst_h) {
                        if ($dst_w && ! $dst_h) {  //有宽无高
                            $propor = $dst_w / $src_w;
                            $height = $dst_h = $src_h * $propor;
                        } else {
                            if (! $dst_w && $dst_h) {  //有高无宽
                                $propor = $dst_h / $src_h;
                                $width  = $dst_w = $src_w * $propor;
                            }
                        }
                    }
                }
            } else {
                if (! $dst_h) {  //裁剪时无高
                    $height = $dst_h = $dst_w;
                }
                if (! $dst_w) {  //裁剪时无宽
                    $width = $dst_w = $dst_h;
                }
                $propor = min(max($dst_w / $src_w, $dst_h / $src_h), 1);
                $dst_w  = (int) round($src_w * $propor);
                $dst_h  = (int) round($src_h * $propor);
                $x      = ($width - $dst_w) / 2;
                $y      = ($height - $dst_h) / 2;
            }
        } else {
            $proportion = min($proportion, 1);
            $height     = $dst_h = $src_h * $proportion;
            $width      = $dst_w = $src_w * $proportion;
        }
        $src = @$createfun($src_img);
        if (! $src) {
            Log::error("img2thumb failed", func_get_args());
            return false;
        }
        $dst   = imagecreatetruecolor($width ? $width : $dst_w, $height ? $height : $dst_h);
        $white = imagecolorallocate($dst, 255, 255, 255);
        imagefill($dst, 0, 0, $white);
        if (function_exists('imagecopyresampled')) {
            imagecopyresampled($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
        } else {
            imagecopyresized($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
        }
        $otfunc($dst, $dst_img);
        imagedestroy($dst);
        imagedestroy($src);
        return true;
    }

方法六:CURL 请求

  /**
     * curl post请求
     * @param  [type] $host  [description]
     * @param  [type] $bodys [description]
     * @return [type]        [description]
     */
    public static function curl_post($host, $bodys) 
    {
        $headers = array();
        $bodys   = http_build_query($bodys);
        $url     = $host;

        //根据API的要求,定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");

        $curl  = curl_init();

        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);

        if (1 == strpos("$".$host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $content = curl_exec($curl);

        curl_close($curl);

        return $content;
    }

    /**
     * curl请求数据
     * 
     * @param string $url  请求地址
     * @param array $param 请求参数
     * @param string $contentType 请求参数格式(json)
     * @return boolean|mixed
     */
    public static function https_request($url = '', $param = [], $contentType = '')
    {
        $ch = curl_init();
        
        // 请求地址
        curl_setopt($ch, CURLOPT_URL, $url);
        
        // 请求参数类型
        $param = $contentType == 'json' ? json_encode($param, true) : $param;
        
        // 关闭https验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        // post提交
        if ($param) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        }
        
        // 返回的数据是否自动显示
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        // 执行并接收响应结果
        $output = curl_exec($ch);
        
        // 关闭curl
        curl_close($ch);
        
        return $output !== false ? $output : false;
    }
	
	// curl get 请求
    public static function curl_get($url) 
    {

        if ($ch = curl_init()) {

            // 这里可能失败,是否加大超时时间还是等结果呢?
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
            $content = curl_exec($ch);
            
            curl_close($ch);

            return $content;
        } else {
            echo "系统CURL初始化失败!";
            exit;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值