程序中总会有一些常用的php函数,总结一下:
/**
* 把数组中的所有null变为空字符串
* @author Bruce 2020-09-01
* @param [type] $data [description]
* @return [type] [description]
*/
function no_null($data)
{
array_walk_recursive($data, function (&$val) {
if ($val === null) {
$val = '';
}
});
return $data;
}
// this-is-a-string => thisIsAString
function camelize($input, $separator = '-')
{
return lcfirst(str_replace($separator, '', ucwords($input, $separator)));
}
/**
* 多维数组的key变成camelCase
* @author Bruce 2020-08-25
* @param array $result [description]
* @return [type] [description]
*/
function camel_result($result = [])
{
$result = json_encode($result, 320);
$new = preg_replace_callback('/(?<=")[a-z_]+(?=":)/', function ($matches) {
return snake_to_camel($matches[0]);
}, $result);
return json_decode($new, true);
}
function check_timezone($value) {
try {
new DateTimeZone($value);
} catch (Exception $e) {
return false;
} catch (Throwable $e) {
return false;
}
return true;
}
function getAllHeaders()
{
$keys = ['host', 'connection', 'x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host', 'x-forwarded-port', 'x-real-ip', 'content-length', 'ali-cdn-real-port', 'ali-cdn-real-ip', 'via', 'ali-swift-log-host', 'ali-swift-stat-host', 'x-client-scheme', 'eagleeye-traceid', 'authorization', 'x-encrypt', 'user-agent', 'content-type', 'accept-encoding'];
$headers = array_filter($_SERVER, function ($key) use ($keys) {
$str = strtolower(str_replace(['HTTP_','_'], ['','-'], $key));
return in_array($str, $keys);
}, ARRAY_FILTER_USE_KEY);
return $headers;
}
function getAllHeaders()
{
$headers= array_filter($_SERVER,function ($key){
return substr($key, 0, 5) === 'HTTP_';
},ARRAY_FILTER_USE_KEY);
return $headers;
}
function check_url($value) {
if (!is_string($value)) {
return false;
}
if ($url = parse_url($value, PHP_URL_HOST)) {
try {
return count(dns_get_record($url, DNS_A | DNS_AAAA)) > 0;
} catch (Exception $e) {
return false;
}
}
return false;
}
function check_email($value) {
return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
}
// =================================新加入=====================================
function check_json($value) {
if (!is_scalar($value) && !method_exists($value, '__toString')) {
return false;
}
json_decode($value);
return json_last_error() === JSON_ERROR_NONE;
}
function getIP()
{
static $realip;
if (isset($_SERVER)){
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
$realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
$realip = $_SERVER["HTTP_CLIENT_IP"];
} else {
$realip = $_SERVER["REMOTE_ADDR"];
}
} else {
if (getenv("HTTP_X_FORWARDED_FOR")){
$realip = getenv("HTTP_X_FORWARDED_FOR");
} else if (getenv("HTTP_CLIENT_IP")) {
$realip = getenv("HTTP_CLIENT_IP");
} else {
$realip = getenv("REMOTE_ADDR");
}
}
return $realip;
}
function getCity($ip = '')
{
if($ip == ''){
$url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
$ip=json_decode(file_get_contents($url),true);
$data = $ip;
}else{
$url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
$ip=json_decode(file_get_contents($url));
if((string)$ip->code=='1'){
return false;
}
$data = (array)$ip->data;
}
return $data;
}
/*=====================================================
* 说明:手机号 隐藏 by:Simon
*====================================================*/
function mobile_phone_hidden($phone)
{
$is_what = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i',$phone); //固定电话
if($is_what == 1)
return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i','$1****$2',$phone);
else
return preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);
}
/*=====================================================
* 说明:身份证号 隐藏 by:Simon
*====================================================*/
function id_card_hidden($idcard)
{
$length = strlen($idcard);
$calcLength = $length - 4 - 4;
return substr_replace($idcard, str_repeat('*',$calcLength), 4, $calcLength);
}
/*=====================================================
* 说明:银行卡 隐藏 by:Simon
*====================================================*/
function id_bank_card_hidden($card)
{
$length = strlen($card);
$calcLength = $length - 4 - 4;
return substr_replace($card, str_repeat('*',$calcLength), 4, $calcLength);
}
/*=====================================================
* 函数:http_post_query
* 说明:http请求 by:Simon
====================================================*/
function http_post_query($url, $data) {
$postdata = http_build_query($data);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
return $result;
}
// =================================原始加入=====================================
/**
* 判断手机号码是否合法
* @param $mobile 手机号码
* @return bool
*/
function check_mobile($mobile)
{
$pattern = '/^(0|86|17951)?(888|13[0-9]|15[012356789]|17[0-9]|111|18[0-9]|14[57])[0-9]{8}$/';
if (preg_match($pattern, $mobile)) {
return TRUE;
} else {
return FALSE;
}
}
/**
* 判断中文姓名是否合法
* @param $realname
* @return bool
*/
function checkRealname($realname) {
$patten = '/^[\x{4e00}-\x{9fa5}]+$/u';
if (preg_match($patten, $realname)) {
return TRUE;
} else {
return FALSE;
}
}
function prs() {
$args = func_get_args();
foreach ($args as $value) {
echo '<pre>';
print_r($value);
echo '</pre>';
}
}
/**
* 数组层级缩进转换
* @param array $array
* @param int $pid
* @param int $level
* @return array
*/
function array2level($array, $pid = 0, $level = 1, &$result = [])
{
foreach ($array as $v) {
if ($v['parent_id'] == $pid) {
$v['level'] = $level;
$result[] = $v;
array2level($array, $v['id'], $level + 1, $result);
}
}
return $result;
}
/**
* 构建层级(树状)数组
* @param array $array 要进行处理的一维数组,经过该函数处理后,该数组自动转为树状数组
* @param string $pid 父级ID的字段名
* @param string $child_key_name 子元素键名
* @return array|bool
*/
function array2tree(&$array, $pid = 'parent_id', $child_key_name = 'children') {
$counter = array_children_count($array, $pid);
if ($counter[0] == 0)
return false;
$tree = [];
while (isset($counter[0]) && $counter[0] > 0) {
$temp = array_shift($array);
if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
array_push($array, $temp);
} else {
if ($temp[$pid] == 0) {
$tree[] = $temp;
} else {
$array = array_child_append($array, $temp[$pid], $temp, $child_key_name);
}
}
$counter = array_children_count($array, $pid);
}
return $tree;
}
/**
* 子元素计数器
* @param $array
* @param $pid
* @return array
*/
function array_children_count($array, $pid)
{
$counter = [];
foreach ($array as $item) {
$count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
$count++;
$counter[$item[$pid]] = $count;
}
return $counter;
}
/**
* 把元素插入到对应的父元素$child_key_name字段
* @param $parent
* @param $pid
* @param $child
* @param string $child_key_name 子元素键名
* @return mixed
*/
function array_child_append($parent, $pid, $child, $child_key_name)
{
foreach ($parent as &$item) {
if ($item['id'] == $pid) {
if (!isset($item[$child_key_name]))
$item[$child_key_name] = [];
$item[$child_key_name][] = $child;
}
}
return $parent;
}
/**
* 获取客户端浏览器信息
* @param $agent
* @return string
*/
function getBrowser($agent)
{
$browser = '';
$browser_ver = '';
if (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)) {
$browser = 'OmniWeb';
$browser_ver = $regs[2];
}
if (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs)) {
$browser = 'Netscape';
$browser_ver = $regs[2];
}
if (preg_match('/safari\/([^\s]+)/i', $agent, $regs)) {
$browser = 'Safari';
$browser_ver = $regs[1];
}
if (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs)) {
$browser = 'Internet Explorer';
$browser_ver = $regs[1];
}
if (preg_match('/rv:([^\s|)]+)/i', $agent, $regs)) {
$browser = 'Internet Explorer';
$browser_ver = $regs[1];
}
if (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs)) {
$browser = 'Opera';
$browser_ver = $regs[1];
}
if (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs)) {
$browser = '(Internet Explorer ' . $browser_ver . ') NetCaptor';
$browser_ver = $regs[1];
}
if (preg_match('/Maxthon/i', $agent, $regs)) {
$browser = '(Internet Explorer ' . $browser_ver . ') Maxthon';
$browser_ver = '';
}
if (preg_match('/360SE/i', $agent, $regs)) {
$browser = '(Internet Explorer ' . $browser_ver . ') 360SE';
$browser_ver = '';
}
if (preg_match('/SE 2.x/i', $agent, $regs)) {
$browser = '(Internet Explorer ' . $browser_ver . ') 搜狗';
$browser_ver = '';
}
if (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs)) {
$browser = 'FireFox';
$browser_ver = $regs[1];
}
if (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs)) {
$browser = 'Lynx';
$browser_ver = $regs[1];
}
if (preg_match('/Chrome\/([^\s]+)/i', $agent, $regs)) {
$browser = 'Chrome';
$browser_ver = $regs[1];
}
if ($browser != '') {
return $browser . ' ' . $browser_ver;
} else {
return '未知浏览器';
}
}
/**
* 获取客户端操作系统信息
* @param $agent
* @return bool|string
*/
function getOs($agent) {
$os = false;
if(preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) {
$os = 'Windows Vista';
} else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) {
$os = 'Windows 7';
} else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) {
$os = 'Windows 8';
} else if (preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) {
$os = 'Windows 10';#添加win10判断
} else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) {
$os = 'Windows XP';
} else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) {
$os = 'Windows 2000';
} else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) {
$os = 'Windows NT';
} else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) {
$os = 'Windows 32';
} else if (preg_match('/linux/i', $agent)) {
$os = 'Linux';
} else if (preg_match('/unix/i', $agent)) {
$os = 'Unix';
} else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) {
$os = 'SunOS';
} else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) {
$os = 'IBM OS/2';
} else if (preg_match('/Mac/i', $agent) && preg_match('/PC/i', $agent)) {
$os = 'Macintosh';
} else if (preg_match('/PowerPC/i', $agent)) {
$os = 'PowerPC';
} else if (preg_match('/AIX/i', $agent)) {
$os = 'AIX';
} else if (preg_match('/HPUX/i', $agent)) {
$os = 'HPUX';
} else if (preg_match('/NetBSD/i', $agent)) {
$os = 'NetBSD';
} else if (preg_match('/BSD/i', $agent)) {
$os = 'BSD';
} else if (preg_match('/OSF1/i', $agent)) {
$os = 'OSF1';
} else if (preg_match('/IRIX/i', $agent)) {
$os = 'IRIX';
} else if (preg_match('/FreeBSD/i', $agent)) {
$os = 'FreeBSD';
} else if (preg_match('/teleport/i', $agent)) {
$os = 'teleport';
} else if (preg_match('/flashget/i', $agent)) {
$os = 'flashget';
} else if (preg_match('/webzip/i', $agent)) {
$os = 'webzip';
} else if (preg_match('/offline/i', $agent)) {
$os = 'offline';
} else {
$os = '未知操作系统';
}
return $os;
}
/**
* 根据二维数组的某个字段进行排序
* @param $multi_array
* @param $sort_key
* @param int $sort
* @return bool
*/
function array_multi_sort($multi_array, $sort_key, $sort = SORT_DESC)
{
if (is_array($multi_array)) {
foreach ($multi_array as $row_array) {
if (is_array($row_array)) {
$key_array[] = $row_array[$sort_key];
} else {
return false;
}
}
} else {
return false;
}
array_multisort($key_array, $sort, $multi_array);
return $multi_array;
}
/**
* httpPost请求
* @param url 请求地址
* @param data 请求参数(json)
*/
function post_json_response($url, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($data)
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $response;
}
function millisecond() {
list($t1, $t2) = explode(' ', microtime());
return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)));
}
function jsonApi($data = '', $status = 200, $message = 'successful') {
header('Content-Type:application/json; charset=utf-8');
return json_encode(array(
'code' => $status,
'message' => is_array($message) ? implode("\n", $message) : $message,
'data' => $data
));
}
function flattenArray($array) {
if (!is_array($array)) {
return (array) $array;
}
$arrayValues = array();
foreach ($array as $value) {
if (is_array($value)) {
foreach ($value as $val) {
if (is_array($val)) {
foreach ($val as $v) {
$arrayValues[] = $v;
}
} else {
$arrayValues[] = $val;
}
}
} else {
$arrayValues[] = $value;
}
}
return $arrayValues;
}
/**
* Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing
*
* @param array $array Array to be flattened
* @return array Flattened array
*/
function flattenArrayIndexed($array) {
if (!is_array($array)) {
return (array) $array;
}
$arrayValues = array();
foreach ($array as $k1 => $value) {
if (is_array($value)) {
foreach ($value as $k2 => $val) {
if (is_array($val)) {
foreach ($val as $k3 => $v) {
$arrayValues[$k1.'.'.$k2.'.'.$k3] = $v;
}
} else {
$arrayValues[$k1.'.'.$k2] = $val;
}
}
} else {
$arrayValues[$k1] = $value;
}
}
return $arrayValues;
}
// 读取大文件
public function getbigfile($file_path, $length = 8000)
{
$handle = fopen($file_path, 'rb+');
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, $length);
echo $buffer;
}
fclose($handle);
}
}
/**
* 批量去除键值对
* @param array $value [description]
* @param array $keys [description]
* @return [type] [description]
*/
function multi_unset(array $value, array $keys)
{
foreach ($keys as $key) {
// unset比较特殊,如果有设置就直接删除,如果没有这个key也不会报错,加上判断反而会报错 marked by Bruce <2020-08-06 15:25:09>
unset($value[$key]);
}
return $value;
}
/**
* 获取数组维度
* @author Bruce 2021/2/2
* @param array $array
* @return int
*/
function array_dimensions(array $array)
{
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$d = 0;
foreach ($it as $v)
$it->getDepth() >= $d and $d = $it->getDepth();
return ++$d;
}
// console里面彩色显示要输出的内容
function ddd($obj = null, $desc = ''): void
{
$t = gettype($obj);
$dt = Carbon::now();
$microsecond = substr($dt->microsecond, 0, 3);
$time = $dt->toDateTimeString() . '.' . $microsecond;
if ($obj != null && !is_string($obj)) {
$obj = json_encode($obj);
}
// https://www.if-not-true-then-false.com/2010/php-class-for-coloring-php-command-line-cli-scripts-output-php-output-colorizing-using-bash-shell-colors/
if ($desc) {
echo "\033[1;33m$time\033[0m \033[1;34m$desc\033[0m: \033[1;31m$t\033[0m => $obj" . PHP_EOL;
} else {
echo "\033[1;33m$time\033[0m \033[1;31m$t\033[0m => $obj" . PHP_EOL;
}
}
/**使用ddd
if (is_dev()) {
DbManager::getInstance()->onQuery(function (Result $res, QueryBuilder $builder) {
ddd($builder->getLastQuery(), "getLastQuery");
ddd($res->toArray(), "getResult");
});
}
*/