Home Backend Development PHP Tutorial 16 common php basic functions

16 common php basic functions

Jun 08, 2018 pm 06:04 PM
php

本文给大家汇总了16个常见的php基本函数,涵盖的面很广,这里推荐给大家,希望对大家学习php能够有所帮助。

1.统计数组元素个数

$arr = array(
   '1011,1003,1008,1001,1000,1004,1012',
   '1009',
   '1011,1003,1111'
  );
$result = array();
foreach ($arr as $str) {
 $str_arr = explode(',', $str);
 foreach ($str_arr as $v) {
  // $result[$v] = isset($result[$v]) ? $result[$v] : 0;
  // $result[$v] = $result[$v] + 1;
  $result[$v] = isset($result[$v]) ? $result[$v]+1 : 1;
 }
}
print_r($result);
//Array
(
[1011] => 2
[1003] => 2
[1008] => 1
[1001] => 1
[1000] => 1
[1004] => 1
[1012] => 1
[1009] => 1
[1111] => 1
)
Copy after login

2. 循环删除目录

function cleanup_directory($dir) {
 foreach (new DirectoryIterator($dir) as $file) {
  if ($file->isDir()) {
   if (! $file->isDot()) {
    cleanup_directory($file->getPathname());
   }
  } else {
    unlink($file->getPathname());
  }
 }
  rmdir($dir);
}
Copy after login

3.无限极分类生成树

function generateTree($items){
  $tree = array();
  foreach($items as $item){
    if(isset($items[$item['pid']])){
      $items[$item['pid']]['son'][] = &$items[$item['id']];
    }else{
      $tree[] = &$items[$item['id']];
    }
  }
  return $tree;
}
function generateTree2($items){
  foreach($items as $item)
    $items[$item['pid']]['son'][$item['id']] = &$items[$item['id']];
  return isset($items[0]['son']) ? $items[0]['son'] : array();
}
$items = array(
  1 => array('id' => 1, 'pid' => 0, 'name' => '安徽省'),
  2 => array('id' => 2, 'pid' => 0, 'name' => '浙江省'),
  3 => array('id' => 3, 'pid' => 1, 'name' => '合肥市'),
  4 => array('id' => 4, 'pid' => 3, 'name' => '长丰县'),
  5 => array('id' => 5, 'pid' => 1, 'name' => '安庆市'),
);
print_r(generateTree($items));
/**
 * 如何取数据格式化的树形数据
 */
$tree = generateTree($items);
function getTreeData($tree){
  foreach($tree as $t){
    echo $t[&#39;name&#39;].&#39;<br>&#39;;
    if(isset($t[&#39;son&#39;])){
      getTreeData($t[&#39;son&#39;]);
    }
  }
}
Copy after login

4.数组排序 a - b 是数字数组写法 遇到字符串的时候就要

var test = [&#39;ab&#39;, &#39;ac&#39;, &#39;bd&#39;, &#39;bc&#39;];
test.sort(function(a, b) {
  if(a < b) {
    return -1;
  }
  if(a > b) {
    return 1;
  }
  return 0;
});
Copy after login

5.array_reduce

$raw = [1,2,3,4,5,];
// array_reduce 的第三个参数是 $result 的初始值
array_reduce($raw, function($result, $value) {
  $result[$value] = $value;
  return $result;
}, []);
// [1 => 1, 2 => 2, ... 5 => 5]
Copy after login

6.array_map 闭包中只接受一个或者多个参数,闭包的参数数量和 array_map 本身的参数数量必须一致

$input = [&#39;key&#39; => &#39;value&#39;];
array_map(function($key, $value) {
  echo $key . $value;
}, array_keys($input), $input)
// &#39;keyvalue&#39;
$double = function($item) {
 return 2 * $item;
}
$result = array_map($double, [1,2,3]);
// 2 4 6
Copy after login

7.繁殖兔子

$month = 12;
  $fab = array();
  $fab[0] = 1;
  $fab[1] = 1;
   for ($i = 2; $i < $month; $i++)
   {
     $fab[$i] = $fab[$i - 1] + $fab[$i - 2];
   }
   for ($i = 0; $i < $month; $i++)
   {
     echo sprintf("第{%d}个月兔子为:{%d}",$i, $fab[$i])."<br/>";
   }
Copy after login

8 .datetime

function getCurMonthFirstDay($date)
{
  return date(&#39;Y-m-01&#39;, strtotime($date));
}
 getCurMonthLastDay(&#39;2015-07-23&#39;)
function getCurMonthLastDay($date)
{
  return date(&#39;Y-m-d&#39;, strtotime(date(&#39;Y-m-01&#39;, strtotime($date)) . &#39; +1 month -1 day&#39;));
}
Copy after login

9.加密解密

function encrypt($data, $key)
{
  $key  =  md5($key);
  $x   =  0;
  $len  =  strlen($data);
  $l   =  strlen($key);
  $char  =  &#39;&#39;;
  for ($i = 0; $i < $len; $i++)
  {
    if ($x == $l)
    {
      $x = 0;
    }
    $char .= $key{$x};
    $x++;
  }
  $str  =  &#39;&#39;;
  for ($i = 0; $i < $len; $i++)
  {
    $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
  }
  return base64_encode($str);
}
function decrypt($data, $key)
{
  $key = md5($key);
  $x = 0;
  $data = base64_decode($data);
  $len = strlen($data);
  $l = strlen($key);
  $char = &#39;&#39;;
  for ($i = 0; $i < $len; $i++)
  {
    if ($x == $l)
    {
      $x = 0;
    }
    $char .= substr($key, $x, 1);
    $x++;
  }
  $str = &#39;&#39;;
  for ($i = 0; $i < $len; $i++)
  {
    if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))
    {
      $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
    }
    else
    {
      $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
    }
  }
  return $str;
}
Copy after login

10 . 多维数组降级

function array_flatten($arr) {
  $result = [];
  array_walk_recursive($arr, function($value) use (&$result) {
    $result[] = $value;
  });
  return $result;
}
print_r(array_flatten([1,[2,3],[4,5]]));// [1,[2,3],[4,5]] => [1,2,3,4,5]
// var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
var test = [1,2,3,[4,5,6],[7,8]];
[].concat.apply([], test); // [1,2,3,4,5,6,7,8] 对于 test 数组中的每一个 value, 将它 concat 到空数组 [] 中去,而因为 concat 是 Array 的 prototype,所以我们用一个空 array 作载体
var test1 = [1,2,[3,[4,[5]]]];
function flatten(arr) {
  return arr.reduce(function(pre, cur) {
    if(Array.isArray(cur)) {
      return flatten(pre.concat(cur));
    }
    return pre.concat(cur);
  }, []);
}
// [1,2,3,4,5]
json_encode中文
function json_encode_wrapper ($result)
{
  if(defined(&#39;JSON_UNESCAPED_UNICODE&#39;)){
    return json_encode($result,JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK);
  }else {
    return preg_replace(
      array("#\\\u([0-9a-f][0-9a-f][0-9a-f][0-9a-f])#ie", "/\"(\d+)\"/",),
      array("iconv(&#39;UCS-2&#39;, &#39;UTF-8&#39;, pack(&#39;H4&#39;, &#39;\\1&#39;))", "\\1"),
      json_encode($result)
    );
  }
}
Copy after login

12.二维数组去重

$arr = array(
  array(&#39;id&#39;=>&#39;2&#39;,&#39;title&#39;=>&#39;...&#39;,&#39;ding&#39;=>&#39;1&#39;,&#39;jing&#39;=>&#39;1&#39;,&#39;time&#39;=>&#39;...&#39;,&#39;url&#39;=>&#39;...&#39;,&#39;dj&#39;=>&#39;...&#39;),
  array(&#39;id&#39;=>&#39;2&#39;,&#39;title&#39;=>&#39;...&#39;,&#39;ding&#39;=>&#39;1&#39;,&#39;jing&#39;=>&#39;1&#39;,&#39;time&#39;=>&#39;...&#39;,&#39;url&#39;=>&#39;...&#39;,&#39;dj&#39;=>&#39;...&#39;)
);
function about_unique($arr=array()){ 
  /*将该种二维数组看成一维数组,则   该一维数组的value值有相同的则干掉只留一个,并将该一维   数组用重排后的索引数组返回,而返回的一维数组中的每个元素都是   原始key值形成的关联数组  */  
$keys =array();
  $temp = array();
  foreach($arr[0] as $k=>$arrays) {
  /*数组记录下关联数组的key值*/   
  $keys[] = $k;
  }
  //return $keys;  /*降维*/  
foreach($arr as $k=>$v) {
  $v = join(",",$v); //降维   
  $temp[] = $v;
  }
  $temp = array_unique($temp); //去掉重复的内容  
foreach ($temp as $k => $v){
  /*再将拆开的数组按索引数组重新组装*/   
  $temp[$k] = explode(",",$v); 
  } 
  //return $temp;  /*再将拆开的数组按关联数组key值重新组装*/  
foreach($temp as $k=>$v) {
  foreach($v as $kkk=>$ck) {
   $data[$k][$keys[$kkk]] = $temp[$k][$kkk];
  }
  }
  return $data;
 }
Copy after login

13.格式化字节大小

/**
* 格式化字节大小
* @param number $size   字节数
* @param string $delimiter 数字和单位分隔符
* @return string      格式化后的带单位的大小
* @author 
*/
function format_bytes($size, $delimiter = &#39;&#39;) {
 $units = array(&#39;B&#39;, &#39;KB&#39;, &#39;MB&#39;, &#39;GB&#39;, &#39;TB&#39;, &#39;PB&#39;);
 for ($i = 0; $size >= 1024 && $i < 6; $i++) $size /= 1024;
 return round($size, 2) . $delimiter . $units[$i];
}
Copy after login

14.3分钟前

/**
* 将指定时间戳转换为截止当前的xx时间前的格式 例如 return &#39;3分钟前&#39;&#39;
* @param string|int $timestamp unix时间戳
* @return string
*/
function time_ago($timestamp) {
  $etime = time() - $timestamp;
  if ($etime < 1) return &#39;刚刚&#39;;   
  $interval = array (     
   12 * 30 * 24 * 60 * 60 => &#39;年前 (&#39;.date(&#39;Y-m-d&#39;, $timestamp).&#39;)&#39;,
   30 * 24 * 60 * 60    => &#39;个月前 (&#39;.date(&#39;m-d&#39;, $timestamp).&#39;)&#39;,
   7 * 24 * 60 * 60    => &#39;周前 (&#39;.date(&#39;m-d&#39;, $timestamp).&#39;)&#39;,
   24 * 60 * 60      => &#39;天前&#39;,
   60 * 60         => &#39;小时前&#39;,
   60           => &#39;分钟前&#39;,
   1            => &#39;秒前&#39;
  );
  foreach ($interval as $secs => $str) {
    $d = $etime / $secs;
    if ($d >= 1) {
      $r = round($d);
      return $r . $str;
    }
  };
}
Copy after login

15.身份证号

/**
* 判断参数字符串是否为天朝身份证号
* @param $id 需要被判断的字符串或数字
* @return mixed false 或 array[有内容的array boolean为真]
*/
function is_citizen_id($id) {
  //长度效验 18位身份证中的X为大写
  $id = strtoupper($id);
  if(!(preg_match(&#39;/^\d{17}(\d|X)$/&#39;,$id) || preg_match(&#39;/^\d{15}$/&#39;,$id))) {
   return false;
  }
  //15位老号码转换为18位 并转换成字符串
  $Wi     = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1); 
  $Ai     = array(&#39;1&#39;, &#39;0&#39;, &#39;X&#39;, &#39;9&#39;, &#39;8&#39;, &#39;7&#39;, &#39;6&#39;, &#39;5&#39;, &#39;4&#39;, &#39;3&#39;, &#39;2&#39;); 
  $cardNoSum  = 0;
  if(strlen($id)==16) {
    $id    = substr(0, 6).&#39;19&#39;.substr(6, 9); 
    for($i = 0; $i < 17; $i++) {
     $cardNoSum += substr($id,$i,1) * $Wi[$i];
    } 
    $seq    = $cardNoSum % 11; 
    $id    = $id.$Ai[$seq];
  }
  //效验18位身份证最后一位字符的合法性
  $cardNoSum  = 0;
  $id17    = substr($id,0,17);
  $lastString = substr($id,17,1);
  for($i = 0; $i < 17; $i++) {
    $cardNoSum += substr($id,$i,1) * $Wi[$i];
  } 
  $seq     = $cardNoSum % 11;
  $realString = $Ai[$seq];
  if($lastString!=$realString) {return false;}
  //地域效验
  $oCity    = array(11=>"北京",12=>"天津",13=>"河北",14=>"山西",15=>"内蒙古",21=>"辽宁",22=>"吉林",23=>"黑龙江",31=>"上海",32=>"江苏",33=>"浙江",34=>"安徽",35=>"福建",36=>"江西",37=>"山东",41=>"河南",42=>"湖北",43=>"湖南",44=>"广东",45=>"广西",46=>"海南",50=>"重庆",51=>"四川",52=>"贵州",53=>"云南",54=>"西藏",61=>"陕西",62=>"甘肃",63=>"青海",64=>"宁夏",65=>"新疆",71=>"台湾",81=>"香港",82=>"澳门",91=>"国外");
  $City    = substr($id, 0, 2);
  $BirthYear  = substr($id, 6, 4);
  $BirthMonth = substr($id, 10, 2);
  $BirthDay  = substr($id, 12, 2);
  $Sex     = substr($id, 16,1) % 2 ;//男1 女0
  //$Sexcn    = $Sex?&#39;男&#39;:&#39;女&#39;;
  //地域验证
  if(is_null($oCity[$City])) {return false;}
  //出生日期效验
  if($BirthYear>2078 || $BirthYear<1900) {return false;}
  $RealDate  = strtotime($BirthYear.&#39;-&#39;.$BirthMonth.&#39;-&#39;.$BirthDay);
  if(date(&#39;Y&#39;,$RealDate)!=$BirthYear || date(&#39;m&#39;,$RealDate)!=$BirthMonth || date(&#39;d&#39;,$RealDate)!=$BirthDay) {
    return false;
  }
  return array(&#39;id&#39;=>$id,&#39;location&#39;=>$oCity[$City],&#39;Y&#39;=>$BirthYear,&#39;m&#39;=>$BirthMonth,&#39;d&#39;=>$BirthDay,&#39;sex&#39;=>$Sex);
}
Copy after login

16.获取二维数组中某个key的集合

$user = array( 0 => array( &#39;id&#39; => 1, &#39;name&#39; => &#39;张三&#39;, &#39;email&#39; => &#39;zhangsan@sina.com&#39;, ), 1 => array( &#39;id&#39; => 2, &#39;name&#39; => &#39;李四&#39;, &#39;email&#39; => &#39;lisi@163.com&#39;, ), 2 => array( &#39;id&#39; => 5, &#39;name&#39; => &#39;王五&#39;, &#39;email&#39; => &#39;10000@qq.com&#39;, ), ...... );
$ids = array(); $ids = array_map(&#39;array_shift&#39;, $user);
$ids = array_column($user, &#39;id&#39;);//php5.5
$names = array(); $names = array_reduce($user, create_function(&#39;$v,$w&#39;, &#39;$v[$w["id"]]=$w["name"];return $v;&#39;));
Copy after login

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

PHP制作用户注册系统的详细代码

php实现了CSV格式数据的导入和导出功能

php中存缓分类数据库缓存

The above is the detailed content of 16 common php basic functions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles