<?php
/**
* 只显示数组指定字段
*/
if (!function_exists('only_show')) {
/**
* @param array|object $data
* @param array $fields
* @return array
*/
function only_show($data, $fields = [])
{
if (empty($fields) || empty($data))
return $data;
$newArr = [];
foreach ($fields as $field) {
if (empty($data[$field]))
continue;
$newArr[$field] = $data[$field];
}
return $newArr;
}
}
if (!function_exists('logger')) {
function logger($message, array $options = [])
{
/** @var \Psr\Log\LoggerInterface $logger */
$logger = app(\Psr\Log\LoggerInterface::class);
$default = [
'level' => 'info',
'context' => [],
];
$context = array_get($options, 'context');
if ($context && !is_array($context) && !$context instanceof ArrayAccess) {
$options['context'] = [$context];
}
$options = array_merge($default, $options);
$logger->log($options['level'], $message, $options['context']);
}
}
if (!function_exists('throw_error')) {
/**
* 异常抛出
* @param string $msg
* @param int $code
* @throws \think\Exception
*/
function throw_error($msg = '', $code = 404)
{
throw new \think\Exception($msg, $code);
}
}
if (!function_exists('ymd')) {
/**
* Function ymd
* 方法描述:时间格式化
* Created on 2018/12/25 18:00
* Created by admin.
* @param $date
* @return string
*/
function ymd($date)
{
if (method_exists($date, 'format')) {
return $date->format('Y-m-d');
} else {
return date_create()->format('Y-m-d');
}
}
}
if (!function_exists('is_specify_format_date')) {
/**
* 判断是否为指定格式日期
* @param $date
* @param string $formant
* @return bool
*/
function is_specify_format_date($date, $formant = 'Y-m-d')
{
$a = date_parse_from_format($formant, $date);
if (empty($a['warning_count']) && empty($a['error_count'])) {
return true;
} else {
return false;
}
}
}
if (!function_exists('miss')) {
/**
* @param $var
* @return bool
*/
function miss(&$var)
{
return !isset($var) || empty($var);
}
}
if (!function_exists('ok')) {
/**
* @param $var
* @return bool
*/
function ok(&$var)
{
return isset($var) && !empty($var);
}
}
if (!function_exists('is_date')) {
/**
* 判断是否为日期
* @param $date
* @return bool
*/
function is_date($date)
{
return strtotime($date) ? true : false;
}
}
if (!function_exists('array_trim')) {
/**
* 数组去空格
*/
function array_trim($input)
{
$list = [];
foreach ($input as $key => &$item) {
if (is_string($item)) {
$list[$key] = trim($item);
}
if (is_array($item)) {
$list[$key] = array_trim($item);
}
}
return $list;
}
}
if (!function_exists('divide')) {
/**
* 百分率
* @param $dividend
* @param $divisor
* @param int $precision
* @return float|int
*/
function divide($dividend, $divisor, $precision = 2)
{
if (!is_numeric($dividend) || !is_numeric($divisor)) {
return 0;
}
if ($divisor == 0) {
if ($dividend == 0) {
return 0;
}
return 100;
}
return round(($dividend / $divisor) * 100, $precision);
}
}
if (!function_exists('dataToJavaFormat')) {
/**
* @param $data
* @return mixed
*/
function dataToJavaFormat($data)
{
return collect($data)->map(function ($item, $key) {
$sub['name'] = $key;
if ($key == 'signer') {
$sub['value'] = $item;
} else {
$sub['value'] = is_array($item) ? json_encode($item, JSON_UNESCAPED_UNICODE) : $item;
}
return $sub;
})->values()->toArray();
}
}
if (!function_exists('dataToJavaFormatJson')) {
/**
* @param $data
* @return mixed
*/
function dataToJavaFormatJson($data)
{
return collect($data)->map(function ($item, $key) {
$sub['name'] = $key;
if ($key == 'signer') {
$sub['value'] = $item;
} else {
$sub['value'] = is_array($item) ? json_decode(json_encode($item, JSON_UNESCAPED_UNICODE)) : $item;
}
return $sub;
})->values()->toArray();
}
}
if (!function_exists('dateFilter')) {
/**
* 日期型数据过滤
* @param $date
* @return null
*/
function dateFilter($date)
{
$pattern = '/^((((19|20)\d{2})-(0?[13-9]|1[012])-(0?[1-9]|[12]\d|30))|(((19|20)\d{2})-(0?[13578]|1[02])-31)|(((19|20)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))-0?2-29))$/';
preg_match($pattern, $date, $matchs);
if (empty($matchs)) {
return null;
}
return $date;
}
}
if (!function_exists('numberFilter')) {
/**
* 数值型数据过滤
* @param $number
* @return int
*/
function numberFilter($number)
{
if (is_numeric($number)) {
return $number;
}
return 0;
}
}
if (!function_exists('request_id')) {
/**获取日志id
* @return string
*/
function request_id()
{
return microtime() . request()->cookie('PHPSESSID');
}
}
if (!function_exists('last_value')) {
function last_value($arr)
{
if (empty($arr))
return $arr;
end($arr);
$last_key = key($arr);
reset($arr);
return $arr[$last_key];
}
}
if (!function_exists('_trim')) {
function _trim($item)
{
$item = preg_replace("/\\s/", '', $item);
$item = trim($item);
return $item;
}
}
if (!function_exists('duplicate')) {
function duplicate($raw)
{
return clone $raw;
}
}
if (!function_exists('vali_array_element')) {
function vali_array_element($array, $element_location, $strict = false)
{
if (isset($array[current($element_location)]) && (!empty($array[current($element_location)]) || $strict === false)) {
$current_location = current($element_location);//当前位置
$current_value = $array[$current_location];//当前位置的值
array_shift($element_location);//下一个位置
if (!empty($element_location) && $element_location != 0) {
return vali_array_element($current_value, $element_location);
}
return true;
} else {
return false;
}
}
}
if (!function_exists('get_array_element')) {
/**
* @param $array
* @param $location
* @param bool $shut_echo
* @param bool $strict 强制验证
* @return bool|null
*/
function get_array_element($array, $location, $shut_echo = false, $strict = false)
{
if (is_numeric($location)) {
$location = (string)$location;
}
if (is_string($location)) {
$location = explode('.', $location);
}
if (vali_array_element($array, $location, $strict)) {
foreach ($location as $element_locationRow) {
$array = $array[$element_locationRow];
}
return $array;
} else {
if ($shut_echo !== true && $shut_echo !== false) {
return $shut_echo;
}
return $shut_echo ? false : null;
}
}
}
/**
* 隐藏账户中间几位
*/
if (!function_exists('hidden_account')) {
function hidden_account($param) {
if (empty($param)) return $param;
//按4的倍数替换成 *
$replacement = str_repeat('*', floor(abs(strlen($param) - 7) / 4) * 4);
return preg_replace('/(.{3})\d+(.{4})/', '$1' . $replacement . '$2', $param);
}
}
if (!function_exists('convertUnderline')) {
/**
* 下划线转驼峰
*/
function convertUnderline($str)
{
$str = preg_replace_callback('/([-_]+([a-z]{1}))/i',function($matches){
return strtoupper($matches[2]);
},$str);
return $str;
}
}
if (!function_exists('humpToLine')) {
/**
* 驼峰转下划线
*/
function humpToLine($str){
$str = preg_replace_callback('/([A-Z]{1})/',function($matches){
return '_'.strtolower($matches[0]);
},$str);
return $str;
}
}
if (!function_exists('dump2file')) {
/**
* 测试打印文件
* @param $vars
* @param bool $return
* @param string $filename
*/
function dump2file($vars, $return = false, $filename = 'debug_log.txt')
{
$m_time = microtime();
list($t1, $t2) = explode(' ', $m_time);
$t1 = $t1 * 1000000;
$t2 = date('Y-m-d H:i:s', $t2);
$flag = $t2 . ' & ' . $t1;
if ($return == true) {
print_r($vars, false);
die;
} else {
// $import_data = print_r($vars, true);
$import_data = json_encode($vars, JSON_UNESCAPED_UNICODE);
}
$filename = env('DOC_PATH') . $filename;
$import_data = "========================= " . $flag . " =========================\r\n\r\n" . $import_data . "\r\n\r\n";
file_put_contents($filename, $import_data, FILE_APPEND);
// list($absolute, $fileAddress) = explode('public', $filename);
// echo "输出至 => public" . $fileAddress;
// die;
}
}
/***********************
**功能:将多维数组合并为一位数组
**$array:需要合并的数组
**$clearRepeated:是否清除并后的数组中得重复值
***********************/
if (!function_exists('array_multiToSingle')) {
function array_multiToSingle($array,$clearRepeated=false){
if(!isset($array)||!is_array($array)||empty($array)){
return false;
}
if(!in_array($clearRepeated,array('true','false',''))){
return false;
}
static $result_array=array();
foreach($array as $value){
if(is_array($value)){
array_multiToSingle($value);
}else{
$result_array[]=$value;
}
}
if($clearRepeated){
$result_array=array_unique($result_array);
}
return $result_array;
}
}
/**
* 异常抛出
*/
if (!function_exists('throw_error')) {
/**
* @param string $msg
* @param int $code
* @throws \think\Exception
*/
function throw_error($msg = '', $code = 404) {
throw new \think\Exception($msg, $code);
}
}
if (!function_exists('days_to_years')) {
/**
* 天数转年
* @param $days
* @return string
*/
function days_to_years($days) {
$years = floor($days / 365);
$days = $days - $years * 365;
return sprintf('%s年%s天', $years, $days);
}
}
if (!function_exists('time_to_days')) {
/**
* 时间戳转天数
* @param $timestr
* @return float
*/
function time_to_days($timestr) {
return ceil($timestr / (3600 * 24));
}
}
if (!function_exists('seconds_to_hour')) {
/**
* 秒转小时.分钟
* @param $seconds
* @return array
*/
function seconds_to_hour($seconds) {
$hour = floor($seconds / 3600);
$min = floor($seconds - ($hour * 3600)) / 60;
$seconds = floor($seconds - ($hour * 3600) - ($min * 60));
return [
'hour' => (int)$hour,
'min' => (int)$min,
'seconds' => (int)$seconds
];
}
}
if (!function_exists('output_array')) {
/**
* 将数据转换为数组格式
* @param $data
* @return mixed
*/
function output_array($data)
{
return json_decode(json_encode($data), true);
}
}
if (!function_exists('meta')) {
/**
* 列表查询返回参数
* @param $data
* @return mixed
*/
function meta($current_page,$limit,$count,$path='',$form='',$to='')
{
return [
'current_page'=> (int) $current_page,
'last_page' => (int) ceil($count/$limit),
'per_page' => (int) $limit,
'total' => (int) $count,
'path' => $path,
'from'=> $form,
'to' => $to
];
}
}
if (!function_exists('is_allow')) {
/**
* 支持数组和字符串,字符串必须为单个权限,数组为多个权限,严格模式为必须全部满足,宽松模式为只要满足其中之一即可
* @param $permission_name //权限名称
* @param bool $is_strict true-严格模式 false-宽松模式
* @param null $uid 用户id
* @return bool
*/
function is_allow($permission_name, $is_strict = false, $uid = null)
{
if (empty($permission_name)) {
return true;
}
if (empty($uid)) {
$user_id = session('uid');
if (empty($user_id)) {
return false;
} else {
$uid = $user_id;
}
}
return \app\facade\PowerApi::powers($permission_name, $uid, $is_strict, 'can');
}
}
常用助手函数(一)
最新推荐文章于 2024-11-07 16:00:23 发布
本文介绍了一系列PHP实用函数,包括数据字段提取、日志记录、错误处理、日期格式化、数据验证等,提升开发效率,适用于前端后端开发工作。
1167

被折叠的 条评论
为什么被折叠?



