常用PHP方法
程序员文章站
2024-01-20 17:08:58
个人常用的一些方法记录/** * 返回错误 * * @param int $err_no * @param string $err_msg * @param array $data * @return array */ function returnError($err_no = 0, $err_m... ......
个人常用的一些方法记录
/** * 返回错误 * * @param int $err_no * @param string $err_msg * @param array $data * @return array */ function returnError($err_no = 0, $err_msg = '', $data = []) { // 错误配置 $config = config('error'); // 错误信息 $error = [ 'err_no' => $err_no, 'err_msg' => empty($err_msg) ? $config[$err_no] : $err_msg, 'data' => $data ]; // 返回 return $error; } /** * 错误响应 * * @param int $err_no * @param string $err_msg * @param array $data * @param string $jsonp * @return \Illuminate\Http\Response */ function response($err_no = 0, $err_msg = '', $data = [], $jsonp = '') { // 错误配置 $config = config('error'); // 错误信息 $error = [ 'err_no' => $err_no, 'err_msg' => empty($err_msg) ? $config[$err_no] : $err_msg, 'data' => $data ]; // 格式化 $result = response()->json($error); empty($jsonp) || $result->setCallback($jsonp); // 返回 return $result; } /** * CURL * * @param string $url * @param string $type * [GET|POST] * @param array|string $data * @param array $header * @return bool|string */ function curlRequest($url = '', $type = 'GET', $data = '', $header = []) { // 参数校验 if (empty($url) || ! in_array(strtoupper($type), [ 'GET', 'POST', 'PUT', 'DELETE' ])) { return false; } // 初始化 $ch = curl_init(); if (! $ch) { return false; } // 请求参数 $data = is_array($data) ? http_build_query($data) : $data; // 请求方式 if (strtoupper($type) == 'POST') { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } if (strtoupper($type) == 'GET') { empty($data) || $url .= '?' . $data; } if (strtoupper($type) == 'PUT') { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } if (strtoupper($type) == 'DELETE') { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); } // 通用配置 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); // 头信息 if (! empty($header)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $header); } // 执行请求 $result = curl_exec($ch); // 错误信息 // $err_no = curl_errno($ch); // $err_info = curl_getinfo($ch); // 关闭资源 curl_close($ch); // 返回 return $result; } /** * 数组转XML[解析:simplexml_load_string($param, 'SimpleXMLElement', LIBXML_NOCDATA)] * * @param array $param * @return string */ function convertXml($param = []) { // 初始化 $xml = ''; // 循环 foreach ($param as $k => $v) { $xml .= "<{$k}><![CDATA[{$v}]]></{$k}>"; } // 返回 return sprintf('<xml>%s</xml>', $xml); } /** * 写入日志|自定义文件 * * @param string $file * @param array $logs * @return bool */ function debug($file = 'debug', $logs = [], $code = 'Debug') { // 文件路径 $path = storage_path("logs/{$file}.log"); // 日志内容 $data = sprintf('[%s] %s %s%s', date('Y-m-d H:i:s'), $code, json_encode($logs, 320), PHP_EOL); // 写入日志 $result = file_put_contents($path, $data, FILE_APPEND); // 返回 return $result === false ? false : true; } /** * 导出CSV * * @param string $filename * @param string $data */ function exportCsv($filename = '', $data = array()) { header("Content-type:text/csv"); header("Content-Disposition:attachment;filename={$filename}.csv"); header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); header('Expires:0'); header('Pragma:public'); $output = ''; foreach ($data as $v) { foreach ($v as $v2) { $output .= mb_convert_encoding($v2, 'GBK', 'UTF-8') . ','; } $output .= "\n"; } exit($output); } /** * 获取当前URL * * @return string */ function getCurrUrl() { $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://'; $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : ''; $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info); $curr_url = $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url; return urlencode($curr_url); } /** * 生成唯一ID * * @return string */ function uniqueId() { // 时间+随机数 return sprintf('%s%04s', date('YmdHis'), mt_rand(0, 9999)); } /** * 根据字典名称获取数据字典 * * @param string $name * @return mixed */ function getConf($name = '', $site_id = 0) { if (empty($name)) { return false; } $data = DB::table('dictionary')->where('site_id', $site_id) ->where('name', strtolower($name)) ->first(); if ($data) { // 单值模式 if ($data['type_id'] == 1) { return json_decode($data['value'], true); } elseif ($data['type_id'] == 2) { // 查询字典列表 $list = DB::table('dictionary_list')->select([ 'key_name', 'key_value' ]) ->where('dictionary_id', $data['id']) ->get() ->toArray(); return empty($list) ? [] : $list; } } return false; } /** * 格式化金额|四舍五入保留2位小数 * * @param float $money * @return string */ function moneyFormat($money = 0) { // 格式化并返回 return sprintf('%.2f', floatval($money)); } /** * 数组排序 * * @param string $key * @param array $arr * @param number $order * @return boolean|multitype */ function arrSort($key = '', $arr = [], $order = 1) { $res = []; // 产生结构数组 foreach ($arr as $k => $v) { $res[$v[$key]] = isset($res[$v[$key]]) ? array_merge($res[$v[$key]], [ $k ]) : [ $k ]; } if ($order == 1) { // 升序 ksort($res); } elseif ($order == 0) { // 降序 krsort($res); } else { return false; } $rs = []; // 组装数组 foreach ($res as $value) { foreach ($value as $n) { $rs[] = $arr[$n]; } } // 返回结果 return $rs; } /** * 计算每期的日期(当前日减一天|当月不足则取最后一天) * * @param string $start_date * @param int $total_month * @param bool $return_last * @return array|string */ function calculateDate($start_date, $total_month, $return_last = false) { // 开始时间 $start_day = intval(date('j', strtotime($start_date))); $start_time = strtotime('-1 day', strtotime($start_date)); // 当前年月日 $curr_year = intval(date('Y', $start_time)); $curr_month = intval(date('n', $start_time)); $curr_day = intval(date('j', $start_time)); // 格式化数组 $date = [ $start_date ]; // 循环计算 for ($i = 1; $i <= $total_month; $i ++) { // 年 if (($curr_month + $i) % 12 == 0) { $year = $curr_year + ($curr_month + $i) / 12 - 1; } else { $year = $curr_year + floor(($curr_month + $i) / 12); } // 月 $month = ($curr_month + $i) % 12; $month = ($month == 0 ? 12 : $month); // 日 $curr_month_days = intval(date('t', strtotime("{$year}-{$month}-01"))); $day = $start_day == 1 ? $curr_month_days : min($curr_day, $curr_month_days); // 当期时间 $date[] = sprintf('%04d-%02d-%02d', $year, $month, $day); } // 返回 if ($return_last) { // 返回最后一期 return array_pop($date); } else { // 返回所有日期 return $date; } } /** * 验证手机是否有效 */ function isMobile($subject = '') { $pattern = "/^1[3|4|5|7|8][0-9]{9}$/"; if (preg_match($pattern, $subject)) { return true; } return false; } /** * 数字转中文 * * @param unknown $num * @param number $m */ function numberToChinese($num) { $CNum = [ [ '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' ], [ '', '十', '百', '千' ], [ '', '万', '亿', '万亿' ] ]; // 验证是否是数字 if (! is_numeric($num)) { return false; } $flt = ''; if (is_integer($num)) { $num = strval($num); } else if (is_numeric($num)) { $num = strval($num); $rs = explode('.', $num, 2); $num = $rs[0]; $flt = $rs[1]; } $len = strlen($num); $num = strrev($num); $chinese = ''; for ($i = 0, $k = 0; $i < $len; $i += 4, $k ++) { $tmp_str = ''; $str = strrev(substr($num, $i, 4)); $str = str_pad($str, 4, '0', STR_PAD_LEFT); for ($j = 0; $j < 4; $j ++) { if ($str{$j} !== '0') { $tmp_str .= $CNum[0][$str{$j}] . $CNum[1][4 - 1 - $j]; } } $tmp_str .= $CNum[2][$k]; $chinese = $tmp_str . $chinese; unset($str); } if ($flt !== '') { $str = ''; for ($i = 0; $i < strlen($flt); $i ++) { $str .= $CNum[0][$flt{$i}]; } $chinese .= "点{$str}"; } return $chinese; } /** * 数字金额转换成中文大写金额的函数 * String Int $num 要转换的小写数字或小写字符串 * return 大写字母 * 小数位为两位 */ function getAmount($num) { $c1 = "零壹贰叁肆伍陆柒捌玖"; $c2 = "分角元拾佰仟万拾佰仟亿"; $num = round($num, 2); $num = $num * 100; if (strlen($num) > 10) { return "数据格式错误"; } $i = 0; $c = ""; while (1) { if ($i == 0) { $n = substr($num, strlen($num) - 1, 1); } else { $n = $num % 10; } $p1 = substr($c1, 3 * $n, 3); $p2 = substr($c2, 3 * $i, 3); if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) { $c = $p1 . $p2 . $c; } else { $c = $p1 . $c; } $i = $i + 1; $num = $num / 10; $num = (int) $num; if ($num == 0) { break; } } $j = 0; $slen = strlen($c); while ($j < $slen) { $m = substr($c, $j, 6); if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') { $left = substr($c, 0, $j); $right = substr($c, $j + 3); $c = $left . $right; $j = $j - 3; $slen = $slen - 3; } $j = $j + 3; } if (substr($c, strlen($c) - 3, 3) == '零') { $c = substr($c, 0, strlen($c) - 3); } if (empty($c)) { return "零元整"; } else { return $c . "整"; } }