paginate($per_page, $columns, 'page', $page)->toArray(); $data['total'] = $return['total']; $data['data'] = $return['data']; return $data; } //分页共用2 public function limitData($db, $columns, $request) { $per_page = $request['page_size'] ?? 1000; $page = $request['page_index'] ?? 1; $return = $db->paginate($per_page, $columns, 'page', $page)->toArray(); return $return['data']; } //抽象一个查询条件,省的每天写很多行 protected function is_exist_db($data, $word, $words, $db, $formula = '=', $type = '') { if (isset($data[$word]) && ($data[$word] !== null && $data[$word] !== '' && $data[$word] !== [])) { switch ($type) { case 'time': $data[$word] = ctype_digit($data[$word]) ? $data[$word] : strtotime($data[$word]); if ($formula == '<'||$formula == '<=') $data[$word] += 86400; $db = $db->where($words, $formula, $data[$word]); break; case 'like': $db = $db->where($words, $type, '%' . $data[$word] . '%'); break; case 'in': if (is_array($data[$word])) { $db = $db->wherein($words, $data[$word]); } else { $db = $db->wherein($words, explode(',', $data[$word])); } break; default: $db = $db->where($words, $formula, $data[$word]); break; } return $db; } return $db; } //判断是否为空 protected function isEmpty($data, $word) { if (isset($data[$word]) && (!empty($data[$word]) || $data[$word] === '0'|| $data[$word] === 0)) return false; return true; } //递归处理数据成子父级关系 public function makeTree($parentId, &$node) { $tree = []; foreach ($node as $key => $value) { if ($value['parent_id'] == $parentId) { $tree[$value['id']] = $value; unset($node[$key]); if (isset($tree[$value['id']]['children'])) { $tree[$value['id']]['children'] = array_merge($tree[$value['id']]['children'], $this->makeTree($value['id'], $node)); } else { $tree[$value['id']]['children'] = $this->makeTree($value['id'], $node); } } } return $tree; } //进行递归处理数组的排序问题 public function set_sort_circle($data){ foreach ($data as $k=>$v){ // var_dump($v);die; if(isset($v['children'])&&!empty($v['children'])){ $data[$k]['children'] = $this->set_sort_circle($v['children']); } } $data = array_merge($data); return $data; } //根据编码规则获取每一级的code public function get_rule_code($code, $rule) { $rules = []; $num = 0; foreach ($rule as $v) { $num += $v['num']; $code = substr($code, 0, $num); if (strlen($code) != $num) continue; $rules[] = $code; } return $rules; } function curlOpen($url, $config = array()) { $arr = array('post' => false,'referer' => $url,'cookie' => '', 'useragent' => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; customie8)', 'timeout' => 100, 'return' => true, 'proxy' => '', 'userpwd' => '', 'nobody' => false,'header'=>array(),'gzip'=>true,'ssl'=>true,'isupfile'=>false,'returnheader'=>false,'request'=>'post'); $arr = array_merge($arr, $config); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, $arr['return']); curl_setopt($ch, CURLOPT_NOBODY, $arr['nobody']); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_USERAGENT, $arr['useragent']); curl_setopt($ch, CURLOPT_REFERER, $arr['referer']); curl_setopt($ch, CURLOPT_TIMEOUT, $arr['timeout']); curl_setopt($ch, CURLOPT_HEADER, $arr['returnheader']);//��ȡheader if($arr['gzip']) curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); if($arr['ssl']) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } if(!empty($arr['cookie'])) { curl_setopt($ch, CURLOPT_COOKIEJAR, $arr['cookie']); curl_setopt($ch, CURLOPT_COOKIEFILE, $arr['cookie']); } if(!empty($arr['proxy'])) { //curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); curl_setopt ($ch, CURLOPT_PROXY, $arr['proxy']); if(!empty($arr['userpwd'])) { curl_setopt($ch,CURLOPT_PROXYUSERPWD,$arr['userpwd']); } } //ip�Ƚ����⣬�ü�ֵ��ʾ if(!empty($arr['header']['ip'])) { array_push($arr['header'],'X-FORWARDED-FOR:'.$arr['header']['ip'],'CLIENT-IP:'.$arr['header']['ip']); unset($arr['header']['ip']); } $arr['header'] = array_filter($arr['header']); if(!empty($arr['header'])) { curl_setopt($ch, CURLOPT_HTTPHEADER, $arr['header']); } if($arr['request'] === 'put'){ curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS,$arr['post']); }elseif($arr['post'] != false) { curl_setopt($ch, CURLOPT_POST, true); if(is_array($arr['post']) && $arr['isupfile'] === false) { $post = http_build_query($arr['post']); } else { $post = $arr['post']; } curl_setopt($ch, CURLOPT_POSTFIELDS, $post); } $result = curl_exec($ch); curl_close($ch); return $result; } function getAllIdsArr($data, $pid = 0, $prefix = '', &$result = []) { foreach ($data as $node) { if ($node['parent_id'] == $pid) { $id = $prefix . $node['id']; $result[] = $id; $this->getAllIdsArr($data, $node['id'], $id . ',', $result); } } return $result; } function getLongestStr($arr = [], $searchStr){ if(empty($arr) || ! $searchStr) return ''; if(! is_string($searchStr)) $searchStr = (string)$searchStr; $longest = ''; foreach ($arr as $str) { if (strpos($str, $searchStr) !== false && strlen($str) > strlen($longest)) { $longest = $str; } } return $longest; } function getAllDescendants($data, $id) { $result = array(); // 存储结果的数组 foreach ($data as $node) { if ($node['parent_id'] == $id) { // 如果当前节点的父 ID 等于指定 ID,则将该节点添加到结果中 $result[] = $node['id']; // 递归查询该节点的所有子孙节点,并将结果合并到结果数组中 $result = array_merge($result, $this->getAllDescendants($data, $node['id'])); } } return $result; } //后台端 某些需要限制请求频率的接口 //需要主动删除 Redis::del($key) public function limitingSendRequest($key,$value=0){ $prefix = config('app.name') . ':'; $key = $prefix . $key; if(! empty($value)) $value = 1; // 使用Redis Facade设置,当键名不存在时才设置成功 if (Redis::setnx($key, $value)) return [true, '']; return [false,'操作频繁!']; } public function delLimitingSendRequest($key){ $prefix = config('app.name') . ':'; $key = $prefix . $key; Redis::del($key); } //后台端 某些需要限制请求频率的接口 有过期时间 public function limitingSendRequestBackgExpire($key,$ttl = 5){ $prefix = config('app.name') . ':'; $key = $prefix . $key; if($ttl < 5) $ttl = 5; // 使用Redis Facade设置,当键名不存在时才设置成功 if (Redis::setnx($key, 1)) { Redis::expire($key, $ttl); //多少秒后过期 return [true, '']; } return [false,'操作频繁, 请在 ' . $ttl . '秒后重试']; } //前端传来的时间段 转换为时间戳 //精确到秒 function changeDateToTimeStampAboutRange($time_range, $is_end = true){ if(empty($time_range[0]) || empty($time_range[1])) return []; // 创建一个 DateTime 对象并设置时区为 UTC $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC')); $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC')); // 将时区设置为 PRC $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai')); $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai')); // 将日期时间格式化为特定格式 $formattedDate = $dateTime->format('Y-m-d'); $formattedDate1 = $dateTime1->format('Y-m-d'); $str = " 23:59:59"; if(! $is_end) $str = " 00:00:00"; $return = []; $return[] = strtotime($formattedDate . " 00:00:00"); $return[] = strtotime($formattedDate1 . $str); return $return; } //前端传来的时间段 转换为时间戳 //精确到日 function changeDateToNewDate($time_range){ if(empty($time_range[0]) || empty($time_range[1])) return []; // 创建一个 DateTime 对象并设置时区为 UTC $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC')); $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC')); // 将时区设置为 PRC $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai')); $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai')); // 将日期时间格式化为特定格式 $formattedDate = $dateTime->format('Y-m-d'); $formattedDate1 = $dateTime1->format('Y-m-d'); $return = []; $return[] = strtotime($formattedDate); $return[] = strtotime($formattedDate1); return $return; } function changeDateToNewDate2($time){ if(empty($time_range)) return []; // 创建一个 DateTime 对象并设置时区为 UTC $dateTime = new \DateTime($time_range, new \DateTimeZone('UTC')); // 将时区设置为 PRC $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai')); // 将日期时间格式化为特定格式 $formattedDate = $dateTime->format('Y-m-d 00:00:00'); $formattedDate1 = $dateTime->format('Y-m-d 23:59:59'); $return = []; $return[] = strtotime($formattedDate); $return[] = strtotime($formattedDate1); return $return; } //前端传来的时间 转为时间戳 //精确到分 function changeDateToDateMin($time){ if(empty($time)) return ''; // 创建一个 DateTime 对象并设置时区为 UTC $dateTime = new \DateTime($time, new \DateTimeZone('UTC')); // 将时区设置为 PRC $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai')); // 将日期时间格式化为特定格式 $formattedDate = $dateTime->format('Y-m-d H:i'); return strtotime($formattedDate); } //前端传来的时间 转为时间戳 //精确到日 function changeDateToDate($time, $is_end = false){ if(empty($time)) return ''; // 创建一个 DateTime 对象并设置时区为 UTC $dateTime = new \DateTime($time, new \DateTimeZone('UTC')); // 将时区设置为 PRC $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai')); $str = "00:00:00"; if($is_end) $str = "23:59:59"; // 将日期时间格式化为特定格式 $formattedDate = $dateTime->format('Y-m-d ' . $str); return strtotime($formattedDate); } /** * 检查数字是否合法,并可验证其正负性和小数位数 * * @param mixed $number 要检查的值 * @param int $decimals 允许的最大小数位数(默认 2) * @param string|null $sign 要求的符号:'positive', 'negative', 'zero', 'non-negative', 'non-positive' null 表示不限制 * @param bool $strict 是否严格模式(不允许整数传字符串等) * @return array ['valid' => bool, 'error' => string|null, 'info' => array] */ public function checkNumber($number, $decimals = 2, $sign = null, $strict = false) { $result = [ 'valid' => false, 'error' => null, 'info' => [] ]; // 1. 类型检查 if ($strict) { if (!is_numeric($number) || is_bool($number)) { $result['error'] = '必须是数字类型'; return $result; } } else { // 宽松模式:允许字符串数字 if (!is_numeric($number)) { $result['error'] = '不是有效数字'; return $result; } } $num = (float)$number; // 统一转为浮点数处理 // 2. 正负号检查 if ($sign !== null) { switch ($sign) { case 'positive': if ($num <= 0) { $result['error'] = '数字必须大于 0'; return $result; } break; case 'negative': if ($num >= 0) { $result['error'] = '数字必须小于 0'; return $result; } break; case 'zero': if ($num != 0) { $result['error'] = '数字必须等于 0'; return $result; } break; case 'non-negative': // 大于等于 0 if ($num < 0) { $result['error'] = '数字必须大于或等于 0'; return $result; } break; case 'non-positive': // 小于等于 0 if ($num > 0) { $result['error'] = '数字必须小于或等于 0'; return $result; } break; default: $result['error'] = "不支持的符号类型: '{$sign}'"; return $result; } } // 3. 小数位数检查 // 将数字转为标准格式,避免科学计数法 $numStr = rtrim(rtrim(sprintf('%.10F', $num), '0'), '.'); // 去除末尾无意义的0 if ($numStr === '' || $numStr === '-') { $numStr = '0'; } // 检查是否有小数点 if (strpos($numStr, '.') === false) { $decimalPlaces = 0; } else { $parts = explode('.', $numStr); $decimalPlaces = strlen($parts[1]); } if ($decimalPlaces > $decimals) { $result['error'] = "小数位数超过 {$decimals} 位(实际 {$decimalPlaces} 位)"; return $result; } // 4. 附加信息 $result['valid'] = true; $result['info'] = [ 'original' => $number, 'value' => $num, 'decimal_places' => $decimalPlaces, 'sign' => $num > 0 ? 'positive' : ($num < 0 ? 'negative' : 'zero'), ]; return $result; } public function getTopId($id, $data) { foreach ($data as $item) { if ($item['id'] == $id) { if ($item['parent_id'] == 0) { // 找到最顶级的id return $item['id']; } else { // 继续递归查找父级 return $this->getTopId($item['parent_id'], $data); } } } // 如果没有找到匹配的id,则返回null或者其他你希望的默认值 return 0; } // 递归查找所有父级id public function findParentIds($id, $data) { $parentIds = []; foreach ($data as $item) { if ($item['id'] == $id) { $parentId = $item['parent_id']; if ($parentId) { $parentIds[] = $parentId; $parentIds = array_merge($parentIds, $this->findParentIds($parentId, $data)); } break; } } return $parentIds; } // 递归查找所有子级id public function findChildIds($id, $data) { $childIds = []; foreach ($data as $item) { if ($item['parent_id'] == $id) { $childId = $item['id']; $childIds[] = $childId; $childIds = array_merge($childIds, $this->findChildIds($childId, $data)); } } return $childIds; } public function getDataFile($data){ foreach ($data as $key => $value){ if($key == 'depart_id' || $key == 'top_depart_id') unset($data[$key]); } return $data; } // 校验域名是否通畅可达 // $domain baidu.com 不要带http这些协议头 // gethostbyname() 函数可能会受到 PHP 配置中的 allow_url_fopen 和 disable_functions 选项的限制 function isDomainAvailable($domain) { $ip = gethostbyname($domain); // 如果解析失败或者返回的 IP 地址与输入的域名相同,则说明域名无效 if ($ip === $domain || filter_var($ip, FILTER_VALIDATE_IP) === false) return false; return true; } public function delStorageFile($old, $new = [], $dir = "upload_files/"){ foreach ($old as $value){ if(! in_array($value, $new)){ $filename_rep = "/api/uploadFiles/"; $filename = str_replace($filename_rep, "", $value); $filePath = $dir . $filename; if (Storage::disk('public')->exists($filePath)) { // 文件存在 进行删除操作 Storage::disk('public')->delete($filePath); } } } } public function showTimeAgo($time, $time_big){ // 计算时间差(秒) $diffInSeconds = $time_big - $time; // 将时间差转换为更易处理的单位 $diffInMinutes = floor($diffInSeconds / 60); $diffInHours = floor($diffInSeconds / 3600); $diffInDays = floor($diffInSeconds / (3600 * 24)); // 根据时间差生成描述性文本 if ($diffInSeconds < 60) { $timeAgo = '刚刚'; } elseif ($diffInMinutes < 60) { $timeAgo = $diffInMinutes . '分钟前'; } elseif ($diffInHours < 24) { $timeAgo = $diffInHours . '小时前'; } elseif ($diffInDays < 2) { $timeAgo = '昨天'; } elseif ($diffInDays < 7) { $timeAgo = $diffInDays . '天前'; } elseif ($diffInDays < 15) { $timeAgo = '一周前'; } elseif ($diffInDays < 30) { $timeAgo = '半个月内'; } else { // 如果超过半个月,可以使用具体的日期格式 $crtTimeDate = date('Y-m-d', $time); $timeAgo = '在 ' . $crtTimeDate; } return $timeAgo; } // 递归函数,用于在数据结构中查找值 function findLabelsByValue($data, $valuesToFind, &$foundLabels) { foreach ($data as $item) { if (isset($item['value']) && in_array($item['value'], $valuesToFind)) { // 如果找到值,则添加其label到结果数组中 $foundLabels[] = $item['label']; // 移除已找到的值,避免重复查找 $key = array_search($item['value'], $valuesToFind); if ($key !== false) { unset($valuesToFind[$key]); } } if (isset($item['children']) && !empty($item['children'])) { // 递归调用自身来查找子节点 $this->findLabelsByValue($item['children'], $valuesToFind, $foundLabels); } // 如果所有值都已找到,则停止递归 if (empty($valuesToFind)) { break; } } } public function changeAndReturnDate($date_int){ $int = intval($date_int); $bool = (string)$int === $date_int; if(! $bool || $date_int < 0) return [false, '日期不正确']; $epoch = strtotime("1900-01-01 00:00:00"); $days = $date_int - 1; $seconds = $days * 86400; return [true,strtotime(date('Y-m-d 00:00:00', $epoch + $seconds))]; } function findTopLevelId($data, $id) { // 遍历数据,查找给定ID的节点 foreach ($data as $item) { if ($item['id'] == $id) { // 如果找到了给定ID的节点,并且它的parent_id为null,则它就是最顶层节点 if ($item['parent_id'] === 0) { return $item['id']; } else { // 否则,继续寻找其父节点的最顶层节点 return $this->findTopLevelId($data, $item['parent_id']); } } } // 如果没有找到给定ID的节点,返回null或抛出异常 return 0; } function returnDays($time = [], $is_mirco_time = false){ // 示例时间戳 $timestamp1 = $time[0]; $timestamp2 = $time[1]; // 计算时间差 $difference = abs($timestamp2 - $timestamp1); // 将时间差转换为天数 $days = floor($difference / (60 * 60 * 24)); if($is_mirco_time) $days = $days / 1000; return $days; } public function post_helper($url, $data, $header = [], $timeout = 30){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_ENCODING, ''); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); if(!is_null($data)) curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $r = curl_exec($ch); if ($r === false) { // 获取错误号 $errorNumber = curl_errno($ch); // 获取错误信息 $errorMessage = curl_error($ch); $message = "cURL Error #{$errorNumber}: {$errorMessage}"; return [false, $message]; } curl_close($ch); return [true, json_decode($r, true)]; } function isOverThreeMonths($timestamp1, $timestamp2, $default_month = 3) { $date1 = new \DateTime(); $date1->setTimestamp($timestamp1); $date2 = new \DateTime(); $date2->setTimestamp($timestamp2); // 计算两个日期的间隔 $interval = $date1->diff($date2); // 总月数 = 年差 * 12 + 月差 $months = $interval->y * 12 + $interval->m; if ($months >= $default_month) { return [false, "时间区间须在" . $default_month . "个月内"]; }elseif ($months == 3 && ($interval->d > 0 || $interval->h > 0 || $interval->i > 0 || $interval->s > 0)) { return [false, "时间区间须在" . $default_month . "个月内"]; } return [true, '']; } public function countTotal($rows, $config = []) { if (empty($rows)) return []; $total = []; foreach ($config as $col) { $key = $col['key'] ?? null; if (!$key) continue; $decimals = $col['decimals'] ?? 2; // 默认保留 2 位 // 1. 基础字段累加 if (!empty($col['sum']) && $col['sum'] == 1) { $sum = '0'; foreach ($rows as $row) { $sum = bcadd($sum, (string)($row[$key] ?? 0), $decimals); } $total[$key] = $sum; } // 2. 公式字段 if (!empty($col['sum']) && $col['sum'] == 2 && !empty($col['formula'])) { $total[$key] = $this->calcFormula($col['formula'], $total, $decimals); } } return $total; } /** * 解析并计算公式(基于 bcmath) * 例: profit / income * 100 */ public function calcFormula($formula, $values, $decimals = 2) { $tokens = preg_split('/\s+/', trim($formula)); $stack = []; foreach ($tokens as $token) { if ($token === '') continue; if (isset($values[$token])) { $stack[] = $values[$token]; } elseif (is_numeric($token)) { $stack[] = (string)$token; } else { $stack[] = $token; } } $expr = implode(' ', $stack); return $this->evaluateWithBCMath($expr, $decimals); } /** * 用 bcmath 安全执行表达式 (支持 + - * /) */ public function evaluateWithBCMath1($expr, $decimals = 2) { // preg_match_all('/(\d+(?:\.\d+)?|[+\/*-])/', $expr, $matches); preg_match_all('/(-?\d+(?:\.\d+)?|[+\/*-])/', $expr, $matches); $tokens = $matches[0] ?? []; if (empty($tokens)) return 0; $output = []; $ops = []; foreach ($tokens as $token) { if (is_numeric($token)) { $output[] = (string)$token; } elseif (in_array($token, ['+', '-', '*', '/'])) { $ops[] = $token; } } $result = array_shift($output); foreach ($ops as $i => $op) { $next = $output[$i] ?? '0'; switch ($op) { case '+': $result = bcadd($result, $next, $decimals); break; case '-': $result = bcsub($result, $next, $decimals); break; case '*': $result = bcmul($result, $next, $decimals); break; case '/': if (bccomp($next, '0', $decimals) === 0) { $result = '0'; // 避免除零 } else { $result = bcdiv($result, $next, $decimals); } break; } } return $result; } public function evaluateWithBCMath($expr, $decimals = 2) { $calcDecimals = 8; // 中间计算用更高精度 // 支持负数和小数 preg_match_all('/-?\d+(?:\.\d+)?|[+\/*-]/', $expr, $matches); $tokens = $matches[0] ?? []; if (empty($tokens)) return '0'; // Shunting-yard 算法转换为逆波兰表达式 (RPN) $output = []; $ops = []; $precedence = ['+' => 1, '-' => 1, '*' => 2, '/' => 2]; foreach ($tokens as $token) { if (is_numeric($token)) { $output[] = (string)$token; } elseif (isset($precedence[$token])) { while (!empty($ops) && $precedence[end($ops)] >= $precedence[$token]) { $output[] = array_pop($ops); } $ops[] = $token; } } while (!empty($ops)) { $output[] = array_pop($ops); } // 计算 RPN $stack = []; foreach ($output as $token) { if (is_numeric($token)) { $stack[] = (string)$token; } else { $b = array_pop($stack) ?? '0'; $a = array_pop($stack) ?? '0'; switch ($token) { case '+': $stack[] = bcadd($a, $b, $calcDecimals); break; case '-': $stack[] = bcsub($a, $b, $calcDecimals); break; case '*': $stack[] = bcmul($a, $b, $calcDecimals); break; case '/': if (bccomp($b, '0', $calcDecimals) === 0) { $stack[] = '0'; } else { $stack[] = bcdiv($a, $b, $calcDecimals); } break; } } } $result = array_pop($stack) ?? '0'; // 最终统一格式化为指定小数位 return bcadd($result, '0', $decimals); } }