php基本函数汇总

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

1.统计数组元素个数

  1. $arr = array(
  2. '1011,1003,1008,1001,1000,1004,1012',
  3. '1009',
  4. '1011,1003,1111'
  5. );
  6. $result = array();
  7. foreach ($arr as $str) {
  8. $str_arr = explode(',', $str);
  9. foreach ($str_arr as $v) {
  10. // $result[$v] = isset($result[$v]) ? $result[$v] : 0;
  11. // $result[$v] = $result[$v] + 1;
  12. $result[$v] = isset($result[$v]) ? $result[$v]+1 : 1;
  13. }
  14. }
  15. print_r($result);
  16. //Array
  17. (
  18. [1011] => 2
  19. [1003] => 2
  20. [1008] => 1
  21. [1001] => 1
  22. [1000] => 1
  23. [1004] => 1
  24. [1012] => 1
  25. [1009] => 1
  26. [1111] => 1
  27. )

2. 循环删除目录

  1. function cleanup_directory($dir) {
  2. foreach (new DirectoryIterator($dir) as $file) {
  3. if ($file->isDir()) {
  4. if (! $file->isDot()) {
  5. cleanup_directory($file->getPathname());
  6. }
  7. } else {
  8. unlink($file->getPathname());
  9. }
  10. }
  11. rmdir($dir);
  12. }

3.无限极分类生成树

  1. function generateTree($items){
  2. $tree = array();
  3. foreach($items as $item){
  4. if(isset($items[$item['pid']])){
  5. $items[$item['pid']]['son'][] = &$items[$item['id']];
  6. }else{
  7. $tree[] = &$items[$item['id']];
  8. }
  9. }
  10. return $tree;
  11. }
  12. function generateTree2($items){
  13. foreach($items as $item)
  14. $items[$item['pid']]['son'][$item['id']] = &$items[$item['id']];
  15. return isset($items[0]['son']) ? $items[0]['son'] : array();
  16. }
  17. $items = array(
  18. 1 => array('id' => 1, 'pid' => 0, 'name' => '安徽省'),
  19. 2 => array('id' => 2, 'pid' => 0, 'name' => '浙江省'),
  20. 3 => array('id' => 3, 'pid' => 1, 'name' => '合肥市'),
  21. 4 => array('id' => 4, 'pid' => 3, 'name' => '长丰县'),
  22. 5 => array('id' => 5, 'pid' => 1, 'name' => '安庆市'),
  23. );
  24. print_r(generateTree($items));
  25. /**
  26. * 如何取数据格式化的树形数据
  27. */
  28. $tree = generateTree($items);
  29. function getTreeData($tree){
  30. foreach($tree as $t){
  31. echo $t['name'].'<br>';
  32. if(isset($t['son'])){
  33. getTreeData($t['son']);
  34. }
  35. }
  36. }

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

  1. var test = ['ab', 'ac', 'bd', 'bc'];
  2. test.sort(function(a, b) {
  3. if(a < b) {
  4. return -1;
  5. }
  6. if(a > b) {
  7. return 1;
  8. }
  9. return 0;
  10. });

5.array_reduce

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

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

  1. $input = ['key' => 'value'];
  2. array_map(function($key, $value) {
  3. echo $key . $value;
  4. }, array_keys($input), $input)
  5. // 'keyvalue'
  6. $double = function($item) {
  7. return 2 * $item;
  8. }
  9. $result = array_map($double, [1,2,3]);
  10. // 2 4 6

7.繁殖兔子

  1. $month = 12;
  2. $fab = array();
  3. $fab[0] = 1;
  4. $fab[1] = 1;
  5. for ($i = 2; $i < $month; $i++)
  6. {
  7. $fab[$i] = $fab[$i - 1] + $fab[$i - 2];
  8. }
  9. for ($i = 0; $i < $month; $i++)
  10. {
  11. echo sprintf("第{%d}个月兔子为:{%d}",$i, $fab[$i])."<br/>";
  12. }

8 .datetime

  1. function getCurMonthFirstDay($date)
  2. {
  3. return date('Y-m-01', strtotime($date));
  4. }
  5. getCurMonthLastDay('2015-07-23')
  6. function getCurMonthLastDay($date)
  7. {
  8. return date('Y-m-d', strtotime(date('Y-m-01', strtotime($date)) . ' +1 month -1 day'));
  9. }

9.加密解密

  1. function encrypt($data, $key)
  2. {
  3. $key = md5($key);
  4. $x = 0;
  5. $len = strlen($data);
  6. $l = strlen($key);
  7. $char = '';
  8. for ($i = 0; $i < $len; $i++)
  9. {
  10. if ($x == $l)
  11. {
  12. $x = 0;
  13. }
  14. $char .= $key{$x};
  15. $x++;
  16. }
  17. $str = '';
  18. for ($i = 0; $i < $len; $i++)
  19. {
  20. $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
  21. }
  22. return base64_encode($str);
  23. }
  24. function decrypt($data, $key)
  25. {
  26. $key = md5($key);
  27. $x = 0;
  28. $data = base64_decode($data);
  29. $len = strlen($data);
  30. $l = strlen($key);
  31. $char = '';
  32. for ($i = 0; $i < $len; $i++)
  33. {
  34. if ($x == $l)
  35. {
  36. $x = 0;
  37. }
  38. $char .= substr($key, $x, 1);
  39. $x++;
  40. }
  41. $str = '';
  42. for ($i = 0; $i < $len; $i++)
  43. {
  44. if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))
  45. {
  46. $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
  47. }
  48. else
  49. {
  50. $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
  51. }
  52. }
  53. return $str;
  54. }

10 . 多维数组降级

  1. function array_flatten($arr) {
  2. $result = [];
  3. array_walk_recursive($arr, function($value) use (&$result) {
  4. $result[] = $value;
  5. });
  6. return $result;
  7. }
  8. print_r(array_flatten([1,[2,3],[4,5]]));// [1,[2,3],[4,5]] => [1,2,3,4,5]
  9. // var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
  10. var test = [1,2,3,[4,5,6],[7,8]];
  11. [].concat.apply([], test); // [1,2,3,4,5,6,7,8] 对于 test 数组中的每一个 value, 将它 concat 到空数组 [] 中去,而因为 concat 是 Array 的 prototype,所以我们用一个空 array 作载体
  12. var test1 = [1,2,[3,[4,[5]]]];
  13. function flatten(arr) {
  14. return arr.reduce(function(pre, cur) {
  15. if(Array.isArray(cur)) {
  16. return flatten(pre.concat(cur));
  17. }
  18. return pre.concat(cur);
  19. }, []);
  20. }
  21. // [1,2,3,4,5]
  22. json_encode中文
  23. function json_encode_wrapper ($result)
  24. {
  25. if(defined('JSON_UNESCAPED_UNICODE')){
  26. return json_encode($result,JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK);
  27. }else {
  28. return preg_replace(
  29. array("#\\\u([0-9a-f][0-9a-f][0-9a-f][0-9a-f])#ie", "/\"(\d+)\"/",),
  30. array("iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", "\\1"),
  31. json_encode($result)
  32. );
  33. }
  34. }

12.二维数组去重

  1. $arr = array(
  2. array('id'=>'2','title'=>'...','ding'=>'1','jing'=>'1','time'=>'...','url'=>'...','dj'=>'...'),
  3. array('id'=>'2','title'=>'...','ding'=>'1','jing'=>'1','time'=>'...','url'=>'...','dj'=>'...')
  4. );
  5. function about_unique($arr=array()){
  6. /*将该种二维数组看成一维数组,则 该一维数组的value值有相同的则干掉只留一个,并将该一维 数组用重排后的索引数组返回,而返回的一维数组中的每个元素都是 原始key值形成的关联数组 */
  7. $keys =array();
  8. $temp = array();
  9. foreach($arr[0] as $k=>$arrays) {
  10. /*数组记录下关联数组的key值*/
  11. $keys[] = $k;
  12. }
  13. //return $keys; /*降维*/
  14. foreach($arr as $k=>$v) {
  15. $v = join(",",$v); //降维
  16. $temp[] = $v;
  17. }
  18. $temp = array_unique($temp); //去掉重复的内容
  19. foreach ($temp as $k => $v){
  20. /*再将拆开的数组按索引数组重新组装*/
  21. $temp[$k] = explode(",",$v);
  22. }
  23. //return $temp; /*再将拆开的数组按关联数组key值重新组装*/
  24. foreach($temp as $k=>$v) {
  25. foreach($v as $kkk=>$ck) {
  26. $data[$k][$keys[$kkk]] = $temp[$k][$kkk];
  27. }
  28. }
  29. return $data;
  30. }

13.格式化字节大小

  1. /**
  2. * 格式化字节大小
  3. * @param number $size 字节数
  4. * @param string $delimiter 数字和单位分隔符
  5. * @return string 格式化后的带单位的大小
  6. * @author
  7. */
  8. function format_bytes($size, $delimiter = '') {
  9. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  10. for ($i = 0; $size >= 1024 && $i < 6; $i++) $size /= 1024;
  11. return round($size, 2) . $delimiter . $units[$i];
  12. }

14.3分钟前

  1. /**
  2. * 将指定时间戳转换为截止当前的xx时间前的格式 例如 return '3分钟前''
  3. * @param string|int $timestamp unix时间戳
  4. * @return string
  5. */
  6. function time_ago($timestamp) {
  7. $etime = time() - $timestamp;
  8. if ($etime < 1) return '刚刚';
  9. $interval = array (
  10. 12 * 30 * 24 * 60 * 60 => '年前 ('.date('Y-m-d', $timestamp).')',
  11. 30 * 24 * 60 * 60 => '个月前 ('.date('m-d', $timestamp).')',
  12. 7 * 24 * 60 * 60 => '周前 ('.date('m-d', $timestamp).')',
  13. 24 * 60 * 60 => '天前',
  14. 60 * 60 => '小时前',
  15. 60 => '分钟前',
  16. 1 => '秒前'
  17. );
  18. foreach ($interval as $secs => $str) {
  19. $d = $etime / $secs;
  20. if ($d >= 1) {
  21. $r = round($d);
  22. return $r . $str;
  23. }
  24. };
  25. }

15.身份证号

  1. /**
  2. * 判断参数字符串是否为天朝身份证号
  3. * @param $id 需要被判断的字符串或数字
  4. * @return mixed false 或 array[有内容的array boolean为真]
  5. */
  6. function is_citizen_id($id) {
  7. //长度效验 18位身份证中的X为大写
  8. $id = strtoupper($id);
  9. if(!(preg_match('/^\d{17}(\d|X)$/',$id) || preg_match('/^\d{15}$/',$id))) {
  10. return false;
  11. }
  12. //15位老号码转换为18位 并转换成字符串
  13. $Wi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1);
  14. $Ai = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
  15. $cardNoSum = 0;
  16. if(strlen($id)==16) {
  17. $id = substr(0, 6).'19'.substr(6, 9);
  18. for($i = 0; $i < 17; $i++) {
  19. $cardNoSum += substr($id,$i,1) * $Wi[$i];
  20. }
  21. $seq = $cardNoSum % 11;
  22. $id = $id.$Ai[$seq];
  23. }
  24. //效验18位身份证最后一位字符的合法性
  25. $cardNoSum = 0;
  26. $id17 = substr($id,0,17);
  27. $lastString = substr($id,17,1);
  28. for($i = 0; $i < 17; $i++) {
  29. $cardNoSum += substr($id,$i,1) * $Wi[$i];
  30. }
  31. $seq = $cardNoSum % 11;
  32. $realString = $Ai[$seq];
  33. if($lastString!=$realString) {return false;}
  34. //地域效验
  35. $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=>"国外");
  36. $City = substr($id, 0, 2);
  37. $BirthYear = substr($id, 6, 4);
  38. $BirthMonth = substr($id, 10, 2);
  39. $BirthDay = substr($id, 12, 2);
  40. $Sex = substr($id, 16,1) % 2 ;//男1 女0
  41. //$Sexcn = $Sex?'男':'女';
  42. //地域验证
  43. if(is_null($oCity[$City])) {return false;}
  44. //出生日期效验
  45. if($BirthYear>2078 || $BirthYear<1900) {return false;}
  46. $RealDate = strtotime($BirthYear.'-'.$BirthMonth.'-'.$BirthDay);
  47. if(date('Y',$RealDate)!=$BirthYear || date('m',$RealDate)!=$BirthMonth || date('d',$RealDate)!=$BirthDay) {
  48. return false;
  49. }
  50. return array('id'=>$id,'location'=>$oCity[$City],'Y'=>$BirthYear,'m'=>$BirthMonth,'d'=>$BirthDay,'sex'=>$Sex);
  51. }

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

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

以上所述就是本文的全部内容了,希望大家能够喜欢。