资讯专栏INFORMATION COLUMN

函数集

marser / 2497人阅读

摘要:统计数组元素个数循环删除目录无限极分类生成树安徽省浙江省合肥市长丰县安庆市如何取数据格式化的树形数据数组排序是数字数组写法遇到字符串的时候就要的第三个参数是的初始值闭包中只接受一个或者多个参数,闭包的参数数量和本身的参数数量必须

统计数组元素个数

</>复制代码

  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. }

print_r($result);
//Array
(

</>复制代码

  1. [1011] => 2
  2. [1003] => 2
  3. [1008] => 1
  4. [1001] => 1
  5. [1000] => 1
  6. [1004] => 1
  7. [1012] => 1
  8. [1009] => 1
  9. [1111] => 1

)

循环删除目录

</>复制代码

  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"]."
    ";
  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.arraymap 闭包中只接受一个或者多个参数,闭包的参数数量和 arraymap 本身的参数数量必须一致

</>复制代码

  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])."
    ";
  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]

11.json_encode中文

</>复制代码

  1. function json_encode_wrapper ($result)
  2. {
  3. if(defined("JSON_UNESCAPED_UNICODE")){
  4. return json_encode($result,JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK);
  5. }else {
  6. return preg_replace(
  7. array("#u([0-9a-f][0-9a-f][0-9a-f][0-9a-f])#ie", "/"(d+)"/",),
  8. array("iconv("UCS-2", "UTF-8", pack("H4", "1"))", "1"),
  9. json_encode($result)
  10. );
  11. }
  12. }

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 falsearray[有内容的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 ;//10
  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;"));

17.判断一个数是否为素数

</>复制代码

  1. function isPrime(number) {
  2. // If your browser doesn"t support the method Number.isInteger of ECMAScript 6,
  3. // you can implement your own pretty easily
  4. if (typeof number !== "number" || !Number.isInteger(number)) {
  5. // Alternatively you can throw an error.
  6. return false;
  7. }
  8. if (number < 2) {
  9. return false;
  10. }
  11. if (number === 2) {
  12. return true;
  13. } else if (number % 2 === 0) {
  14. return false;
  15. }
  16. var squareRoot = Math.sqrt(number);
  17. for(var i = 3; i <= squareRoot; i += 2) {
  18. if (number % i === 0) {
  19. return false;
  20. }
  21. }
  22. return true;
  23. }
  24. function isPrime($n) {//TurkHackTeam AVP production
  25.     if ($n <= 3) {
  26.         return $n > 1;
  27.     } else if ($n % 2 === 0 || $n % 3 === 0) {
  28.         return false;
  29.     } else {
  30.         for ($i = 5; $i * $i <= $n; $i += 6) {
  31.             if ($n % $i === 0 || $n % ($i + 2) === 0) {
  32.                 return false;
  33.             }
  34.         }
  35.         return true;
  36.     }
  37. }

18.闭包

</>复制代码

  1. var nodes = document.getElementsByTagName("button");
  2. for (var i = 0; i < nodes.length; i++) {
  3. nodes[i].addEventListener("click", (function(i) {
  4. return function() {
  5. console.log("You clicked element #" + i);
  6. }
  7. })(i));
  8. }
  9. //将函数移动到循环外部即可(创建了一个新的闭包对象)
  10. function handlerWrapper(i) {
  11. return function() {
  12. console.log("You clicked element #" + i);
  13. }
  14. }
  15. var nodes = document.getElementsByTagName("button");
  16. for (var i = 0; i < nodes.length; i++) {
  17. nodes[i].addEventListener("click", handlerWrapper(i));
  18. }

19.事件循环 Event Loop

</>复制代码

  1. function printing() {
  2. console.log(1);
  3. setTimeout(function() { console.log(2); }, 1000);
  4. setTimeout(function() { console.log(3); }, 0);
  5. console.log(4);
  6. }
  7. //即使setTimeout的延迟为0,其回调也会被加入到那些没有延迟的函数队列之后。
  8. printing();//1432

20.字典排序

</>复制代码

  1. def mysort():
  2. dic = {"a":31, "bc":5, "c":3, "asd":4, "aa":74, "d":0}
  3. dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)
  4. print dict//[("aa", 74), ("a", 31), ("bc", 5), ("asd", 4), ("c", 3), ("d", 0)]

21.数值缩写

</>复制代码

  1. var abbr = function (number) {
  2. var abbrList = ["", "K", "M", "G", "T", "P", "E", "Z", "Y"];
  3. var step = 1000;
  4. var i = 0;
  5. var j = abbrList.length;
  6. while (number >= step && ++i < j) {
  7. number = number / step;
  8. }
  9. if (i === j) {
  10. i = j - 1;
  11. }
  12. return number + abbrList[i];
  13. };

22.数字千位分隔符

</>复制代码

  1. var format = function (number) {
  2. return String(number).replace(/(d)(?=(d{3})+$)/g, "$1,");
  3. };

23.实现随机颜色值

</>复制代码

  1. var randomColor = function () {
  2. var letters = "0123456789ABCDEF";
  3. var ret = "#";
  4. for (var i = 0; i < 6; i++) {
  5. ret += letters[Math.round(Math.random() * 15)];
  6. }
  7. return ret;
  8. };
  9. var randomColor = function () {
  10. return "#" + Math.random().toString(16).substr(2, 6);
  11. };

24.时间格式化输出

</>复制代码

  1. //formatDate(new Date(1409894060000), "yyyy-MM-dd HH:mm:ss 星期w") 2014-09-05 13:14:20 星期五
  2. function formatDate(oDate, sFormation) {
  3. var obj = {
  4. yyyy:oDate.getFullYear(),
  5. yy:(""+ oDate.getFullYear()).slice(-2),//非常精辟的方法
  6. M:oDate.getMonth()+1,
  7. MM:("0"+ (oDate.getMonth()+1)).slice(-2),
  8. d:oDate.getDate(),
  9. dd:("0" + oDate.getDate()).slice(-2),
  10. H:oDate.getHours(),
  11. HH:("0" + oDate.getHours()).slice(-2),
  12. h:oDate.getHours() % 12,
  13. hh:("0"+oDate.getHours() % 12).slice(-2),
  14. m:oDate.getMinutes(),
  15. mm:("0" + oDate.getMinutes()).slice(-2),
  16. s:oDate.getSeconds(),
  17. ss:("0" + oDate.getSeconds()).slice(-2),
  18. w:["日", "一", "二", "三", "四", "五", "六"][oDate.getDay()]
  19. };
  20. return sFormation.replace(/([a-z]+)/ig,function($1){return obj[$1]});
  21. }

25.斐波那契数列

</>复制代码

  1. function fibonacci(n) {
  2. if(n ==1 || n == 2){
  3. return 1
  4. }
  5. return fibonacci(n - 1) + fibonacci(n - 2);
  6. }

26.数组去重

</>复制代码

  1. Array.prototype.distinct=function(){
  2. var arr=[];
  3. var obj={};
  4. for(var i=0;i
  5. 27.删除元素

  6. </>复制代码

    1. function array_delete($array, $element) {
    2. return array_diff($array, [$element]);
    3. // if(($key = array_search($array, $element)) !== false) {
    4. // unset($array[$key]);
    5. // }
    6. //$array = array_filter($array, function($e) use ($del_val) {
    7. // return ($e !== $del_val);
    8. //});
    9. //$array = array(14,22,37,42,58,61,73,82,96,10);
    10. //array_splice($array, array_search(58, $array ), 1);
    11. }
    12. array_delete( [312, 401, 1599, 3], 401 ) // returns [312, 1599, 3]
  7. 28.RandomString

  8. </>复制代码

    1. def random_string(length):
    2. return "".join(random.choice(string.letters + string.digits) for i in xrange(length))
    3. function generateRandomString($length = 10) {
    4. $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    5. $charactersLength = strlen($characters);
    6. $randomString = "";
    7. for ($i = 0; $i < $length; $i++) {
    8. $randomString .= $characters[rand(0, $charactersLength - 1)];
    9. }
    10. return $randomString;
    11. }
    12. //$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
    13. //$string = bin2hex(openssl_random_pseudo_bytes(10));20 char long hexdec string
  9. 29.保存文件

  10. </>复制代码

    1. $ch = curl_init("http://example.com/image.php");
    2. $fp = fopen("/my/folder/flower.gif", "wb");
    3. curl_setopt($ch, CURLOPT_FILE, $fp);
    4. curl_setopt($ch, CURLOPT_HEADER, 0);
    5. curl_exec($ch);
    6. curl_close($ch);
    7. fclose($fp);
  11. 30.插入数组元素

  12. </>复制代码

    1. function array_insert(&$array, $position, $insert)
    2. {
    3. if (is_int($position)) {
    4. array_splice($array, $position, 0, $insert);
    5. } else {
    6. $pos = array_search($position, array_keys($array));
    7. $array = array_merge(
    8. array_slice($array, 0, $pos),
    9. $insert,
    10. array_slice($array, $pos)
    11. );
    12. }
    13. }
    14. $arr = [
    15. "name" => [
    16. "type" => "string",
    17. "maxlength" => "30",
    18. ],
    19. "email" => [
    20. "type" => "email",
    21. "maxlength" => "150",
    22. ],
    23. ];
    24. array_insert(
    25. $arr,
    26. "email",
    27. [
    28. "phone" => [
    29. "type" => "string",
    30. "format" => "phone",
    31. ],
    32. ]
    33. );
    34. // ->
    35. array (
    36. "name" =>
    37. array (
    38. "type" => "string",
    39. "maxlength" => "30",
    40. ),
    41. "phone" =>
    42. array (
    43. "type" => "string",
    44. "format" => "phone",
    45. ),
    46. "email" =>
    47. array (
    48. "type" => "email",
    49. "maxlength" => "150",
    50. ),
    51. )
  13. 31.验证ip

  14. </>复制代码

    1. function validate_ip($ip)
    2. {
    3. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) === false)
    4. return false;
    5. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) === false)
    6. return false;
    7. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false)
    8. return false;
    9. return true;
    10. }
    11. function validate_ip($ip)
    12. {
    13. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false)
    14. {
    15. return false;
    16. }
    17. self::$ip = sprintf("%u", ip2long($ip)); // you seem to want this
    18. return true;
    19. }
  15. 32.get ip

  16. </>复制代码

    1. function get_ip_address(){
    2. foreach (array("HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "REMOTE_ADDR") as $key){
    3. if (array_key_exists($key, $_SERVER) === true){
    4. foreach (explode(",", $_SERVER[$key]) as $ip){
    5. $ip = trim($ip); // just to be safe
    6. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
    7. return $ip;
    8. }
    9. }
    10. }
    11. }
    12. }
  17. 33.选出最长的单词

  18. </>复制代码

    1. function LongestWord(sen) {
    2. var words = sen.match(/w+/g);
    3. if (words !== null) {
    4. var maxWords = {
    5. index: 0,
    6. length: 0
    7. };
    8. for (var i = 0, length = words.length; i < length; i++) {
    9. if (words[i].length > maxWords.length) {
    10. maxWords = {
    11. index: i,
    12. length: words[i].length
    13. }
    14. }
    15. }
    16. return words[maxWords.index];
    17. }
    18. return words;
    19. }
  19. 34.map

  20. </>复制代码

    1. var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];
    2. function getNewArr(){
    3. return oldArr.map(function(item,index){
    4. item.full_name = [item.first_name,item.last_name].join(" ");
    5. return item;
    6. });
    7. }
  21. 35.统计一个数组中有多少个不重复的单词

  22. </>复制代码

    1. var arr = ["apple","orange","apple","orange","pear","orange"];
    2. //https://github.com/es-shims/es5-shim
    3. function getWordCnt(){
    4. var obj = {};
    5. for(var i= 0, l = arr.length; i< l; i++){
    6. var item = arr[i];
    7. obj[item] = (obj[item] +1 ) || 1;//obj[item]为undefined则返回1
    8. }
    9. return obj;
    10. }
    11. function getWordCnt(){
    12. return arr.reduce(function(prev,next){
    13. prev[next] = (prev[next] + 1) || 1;
    14. return prev;
    15. },{});
    16. }
  23. 36.约瑟夫环

  24. </>复制代码

    1. function yuesefu($n,$m) {
    2. $r=0;
    3. for($i=2; $i<=$n; $i++) {
    4. $r=($r+$m)%$i;
    5. }
    6. return $r+1;
    7. }
    8. echo yuesefu(10,3)."是猴王";
  25. 37.判断一个字符串中的字符是否都在另一个中出现

  26. </>复制代码

    1. function charsissubset($h, $n) {
    2. return preg_match("/[^" . preg_quote($h) . "]/u", $n) ? 0 : 1;
    3. }
    4. echo charsissubset("abcddcba", "abcde"); // false
    5. echo charsissubset("abcddcba", "abcd"); // true
    6. echo charsissubset("abcddcba", "badc"); // true
    7. echo charsissubset("汉字", "字"); // true
    8. echo charsissubset("汉字", "漢字"); // false
  27. 38.add(2)(3)(4)

  28. </>复制代码

    1. function add(a) {
    2. var temp = function(b) {
    3. return add(a + b);
    4. }
    5. temp.valueOf = temp.toString = function() {
    6. return a;
    7. };
    8. return temp;
    9. }
    10. var ans = add(2)(3)(4);//9
    11. function add(num){
    12. num += ~~add;
    13. add.num = num;
    14. return add;
    15. }
    16. add.valueOf = add.toString = function(){return add.num};
    17. var ans = add(3)(4)(5)(6); // 18
  29. 39.打印出Fibonacci数

  30. </>复制代码

    1. function fn(n) {
    2. var a = [];
    3. a[0] = 0, a[1] = 1;
    4. for(var i = 2; i < n; i++)
    5. a[i] = a[i - 1] + a[i - 2];
    6. for(var i = 0; i < n; i++)
    7. console.log(a[i]);
    8. }
  31. 40.把URL参数解析为一个对象

  32. </>复制代码

    1. function parseQueryString(url) {
    2. var obj = {};
    3. var a = url.split("?");
    4. if(a.length === 1) return obj;
    5. var b = a[1].split("&");
    6. for(var i = 0, length = b.length; i < length; i++) {
    7. var c = b[i].split("=");
    8. obj[c[0]] = c[1];
    9. }
    10. return obj;
    11. }
    12. var url = "http://witmax.cn/index.php?key0=0&key1=1&key2=2";
    13. var obj = parseQueryString(url);
    14. console.log(obj.key0, obj.key1, obj.key2); // 0 1 2
  33. 41.判断数据类型

  34. </>复制代码

    1. function isNumber(obj) {
    2. return Object.prototype.toString.call(obj) === "[object Number]"
    3. }//对于NaN也返回true
    4. function isNumber(obj) {
    5. return obj === +obj
    6. }
    7. // 判断字符串
    8. function isString(obj) {
    9. return obj === obj+""
    10. }
    11. // 判断布尔类型
    12. function isBoolean(obj) {
    13. return obj === !!obj
    14. }
  35. 42.javascript sleep

  36. </>复制代码

    1. function sleep(numberMillis) {
    2. var now = new Date();
    3. var exitTime = now.getTime() + numberMillis;
    4. while (true) {
    5. now = new Date();
    6. if (now.getTime() > exitTime)
    7. return;
    8. }
    9. }
  37. 43.爬虫

  38. </>复制代码

    1. def splider():
    2. # -*- coding:utf-8 -*-
    3. #发送data表单数据
    4. import urllib2
    5. import urllib
    6. url = "http://www.someserver.com/register.cgi"
    7. values = {
    8. "name" : "Andrew",
    9. "location" : "NJU",
    10. "language" : "Python"
    11. }
    12. user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"
    13. header = {"User-Agent" : user_agent}
    14. data = urllib.urlencode(values) #data数据需要编码成标准形式
    15. #print data
    16. http_handler = urllib2.HTTPHandler(debuglevel = 1)#Debug log
    17. https_handler = urllib2.HTTPSHandler(debuglevel = 1)
    18. opener = urllib2.build_opener(http_handler, https_handler)
    19. urllib2.install_opener(opener)
    20. req = urllib2.Request(url, data) #发送请求同时传送data表单
    21. #req = urllib2.Request(url, data, header) #url 表单数据 伪装头部
    22. reponse = urllib2.urlopen(req, timeout=10) #接受反馈数据
    23. html = reponse.read() #读取反馈数据
    24. print response.info()
    25. print response.getcode()
    26. redirected = response.geturl() == url
    27. """
    28. full_url = url + "?" + data
    29. data = urllib2.open(full_url)
    30. """
    31. #返回错误码, 200不是错误, 不会引起异常
    32. headers = {
    33. "Referer": "http://www.cnbeta.com/articles"
    34. }
    35. proxy_handler = urllib2.ProxyHandler({"http" : "http://some-proxy.com:8080"})
    36. opener = urllib2.build_opener(proxy_handler)
    37. urllib2.install_opener(opener) #urllib2.install_opener() 会设置 urllib2 的全局 opener
    38. req = urllib2.Request(
    39. url = "http://secure.verycd.com/signin/*/http://www.verycd.com/",
    40. data = post_data,
    41. headers = headers
    42. )
    43. try:
    44. urllib2.urlopen(req)
    45. except urllib2.HTTPError, e:
    46. print e.code
    47. #print e.read()
  39. 44.判断数据类型

  40. </>复制代码

    1. function type(o) {
    2. var t, c, n;
    3. if (o === null)
    4. return "null";
    5. if (o !== o)
    6. return "nan";
    7. if ((t = typeof o) !== "object")
    8. return t; // 识别原始值的类型和函数
    9. if ((c = classof(o)) !== "Object")
    10. return c; // 识别出大多数内置类型
    11. if (o.constructor && typeof o.constructor === "function" &&
    12. (n = o.constructor.getName()))
    13. return n; //如果对象构造函数名字存在, 则返回
    14. return "Object"; // 无法识别类型返回"Object"
    15. }
    16. function classof(o) {
    17. return Object.prototype.toString.call(o).slice(8, -1);
    18. }
    19. Function.prototype.getName = function() {
    20. if ("name" in this)
    21. return this.name;
    22. return this.name = this.toString().match(/functions*([^(]*)(/)[1];
    23. }
  41. 45.实现千分位分隔

  42. </>复制代码

    1. function mysplit(s){
    2. if(/[^0-9.]/.test(s)) return "invalid value";
    3. s=s.replace(/^(d*)$/,"$1.");
    4. s=(s+"00").replace(/(d*.dd)d*/,"$1");
    5. s=s.replace(".",",");
    6. var re=/(d)(d{3},)/;
    7. while(re.test(s))
    8. s=s.replace(re,"$1,$2");
    9. s=s.replace(/,(dd)$/,".$1");
    10. return "¥" + s.replace(/^./,"0.")
    11. }
  43. 46.随机产生颜色

  44. </>复制代码

    1. function randomVal(val){
    2. return Math.floor(Math.random()*(val + 1));
    3. }
    4. function randomColor(){
    5. return "rgb(" + randomVal(255) + "," + randomVal(255) + "," + randomVal(255) + ")";
    6. }
  45. 47.生成随机的IP地址,规则类似于192.168.11.0/24

  46. </>复制代码

    1. RANDOM_IP_POOL=["192.168.10.222/0"]
    2. def __get_random_ip():
    3. str_ip = RANDOM_IP_POOL[random.randint(0,len(RANDOM_IP_POOL) - 1)]
    4. str_ip_addr = str_ip.split("/")[0]
    5. str_ip_mask = str_ip.split("/")[1]
    6. ip_addr = struct.unpack(">I",socket.inet_aton(str_ip_addr))[0]
    7. mask = 0x0
    8. for i in range(31, 31 - int(str_ip_mask), -1):
    9. mask = mask | ( 1 << i)
    10. ip_addr_min = ip_addr & (mask & 0xffffffff)
    11. ip_addr_max = ip_addr | (~mask & 0xffffffff)
    12. return socket.inet_ntoa(struct.pack(">I", random.randint(ip_addr_min, ip_addr_max)))
  47. 48.倒计时

  48. </>复制代码

    1. var total = 500;
    2. var timer = null;
    3. var tiktock = document.getElementById("tiktock");
    4. var btn = document.getElementById("btn");
    5. function countdown(){
    6. timer = setInterval(function(){
    7. total--;
    8. if (total<=0) {
    9. clearInterval(timer);
    10. tiktock.innerHTML= "0:00";
    11. }else{
    12. var ss = Math.floor(total/100);
    13. var ms = total-Math.floor(total/100)*100;
    14. tiktock.innerHTML=ss + ":" + ms;
    15. }
    16. },10);
    17. };
    18. btn.addEventListener("click", countdown, false);
  49. 49.[1,2,3] ->"{1,2,3}"

  50. </>复制代码

    1. class intSet(object):
    2. def __init__(self):
    3. # creat an empty set of integers
    4. self.vals = []
    5. def insert(self, e):
    6. # assume e is an interger, and insert it
    7. if not(e in self.vals):
    8. self.vals.append(e)
    9. def member(self, e):
    10. return e in self.vals
    11. def remove(self, e):
    12. try:
    13. self.vals.remove(e)
    14. except:
    15. raise ValueError(str(e) + "not found")
    16. def __str__(self):
    17. # return a string representation of self
    18. self.vals.sort()
    19. return "{" + ",".join([str(e) for e in self.vals]) + "}"
  51. 50.转义过滤

  52. </>复制代码

    1. //纯数字的参数intval强制取整
    2. //其他参数值进行过滤或者转义
    3. //filter_input() 函数来过滤一个 POST 变量
    4. if (!filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL))
    5. {
    6. echo "E-Mail is not valid";
    7. }
    8. else
    9. {
    10. echo "E-Mail is valid";
    11. }
    12. protected function zaddslashes($string, $force = 0, $strip = FALSE)
    13. {
    14. if (!defined("MAGIC_QUOTES_GPC"))
    15. {
    16. define("MAGIC_QUOTES_GPC", "");
    17. }
    18. if (!MAGIC_QUOTES_GPC || $force)
    19. {
    20. if (is_array($string)) {
    21. foreach ($string as $key => $val)
    22. {
    23. $string[$key] = $this->zaddslashes($val, $force, $strip);
    24. }
    25. }
    26. else
    27. {
    28. $string = ($strip ? stripslashes($string) : $string);
    29. $string = htmlspecialchars($string);
    30. }
    31. }
    32. return $string;
    33. }
  53. 51.构造IP

  54. </>复制代码

    1. function getIPaddress()
    2. {
    3.     $IPaddress = "";
    4.     if (isset($_SERVER)) {
    5.         if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
    6.             $IPaddress = $_SERVER["HTTP_X_FORWARDED_FOR"];
    7.         } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
    8.             $IPaddress = $_SERVER["HTTP_CLIENT_IP"];
    9.         } else {
    10.             $IPaddress = $_SERVER["REMOTE_ADDR"];
    11.         }
    12.     } else {
    13.         if (getenv("HTTP_X_FORWARDED_FOR")) {
    14.             $IPaddress = getenv("HTTP_X_FORWARDED_FOR");
    15.         } else if (getenv("HTTP_CLIENT_IP")) {
    16.             $IPaddress = getenv("HTTP_CLIENT_IP");
    17.         } else {
    18.             $IPaddress = getenv("REMOTE_ADDR");
    19.         }
    20.     }
    21.     return $IPaddress;
    22. }
    23. function curlPost($url, $post="", $autoFollow=0){
    24. $ch = curl_init();
    25. $user_agent = "Safari Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.73.11 (KHTML, like Gecko) Version/7.0.1 Safari/5
    26. curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    27. curl_setopt($ch, CURLOPT_URL, $url);
    28. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    29. curl_setopt($ch, CURLOPT_HEADER, 0);
    30. curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-FORWARDED-FOR:61.135.169.125", "CLIENT-IP:".getIPaddress())); //构造IP
    31. curl_setopt($ch, CURLOPT_REFERER, "http://www.baidu.com/"); //构造来路
    32. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    33. if($autoFollow){
    34. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //启动跳转链接
    35. curl_setopt($ch, CURLOPT_AUTOREFERER, true); //多级自动跳转
    36. }
    37. //
    38. if($post!=""){
    39. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    40. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    41. }
    42. $output = curl_exec($ch);
    43. curl_close($ch);
    44. return $output;
    45. }
  55. 52.文件名生成唯一

  56. </>复制代码

    1. function unique_filename() {
    2. $time = !empty($_SERVER["REQUEST_TIME_FLOAT"]) ? $_SERVER["REQUEST_TIME_FLOAT"] : mt_rand();
    3. $addr = !empty($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : mt_rand();
    4. $port = !empty($_SERVER["REMOTE_PORT"]) ? $_SERVER["REMOTE_PORT"] : mt_rand();
    5. $ua = !empty($_SERVER["HTTP_USER_AGENT"]) ? $_SERVER["HTTP_USER_AGENT"] : mt_rand();
    6. return md5(uniqid(mt_rand(), true).$time.$addr.$port.$ua.mt_rand());
    7. }
  57. 53.PHP实现钩子和插件系统

  58. </>复制代码

    1. /**
    2. * Attach (or remove) multiple callbacks to an event and trigger those callbacks when that event is called.
    3. * 绑定或移除多个回调函数到事件,当事件被调用时触发回调函数.
    4. *
    5. * @param string $event name
    6. * @param mixed $value the optional value to pass to each callback
    7. * @param mixed $callback the method or function to call - FALSE to remove all callbacks for event
    8. */
    9. function event($event, $value = NULL, $callback = NULL) {
    10. static $events;
    11. if($callback !== NULL) {
    12. if($callback) {
    13. $events[$event][] = $callback; // 添加事件
    14. } else {
    15. unset($events[$event]); // 移除事件里所有的回调函数
    16. }
    17. } else if(isset($events[$event])) {
    18. foreach($events[$event] as $function) {
    19. $value = call_user_func($function, $value); // 调用事件
    20. }
    21. return $value;
    22. }
    23. }
    24. // 添加事件
    25. event("filter_text", NULL, function($text) { return htmlspecialchars($text); });
    26. event("filter_text", NULL, function($text) { return nl2br($text); });
    27. // 移除事件里所有的回调函数
    28. // event("filter_text", NULL, FALSE);
    29. // 调用事件
    30. $text = event("filter_text", $_POST["text"]);
  59. 54.字符串首字母大写的实现方式

  60. </>复制代码

    1. String.prototype.firstUpperCase = function(){
    2. return this.replace(/(w)(w*)/g, function($0, $1, $2) {
    3. return $1.toUpperCase() + $2.toLowerCase();
    4. });
    5. }
    6. //这只能改变字符串首字母
    7. String.prototype.firstUpperCase=function(){
    8. return this.replace(/^S/,function(s){return s.toUpperCase();});
    9. }
  61. 55.获取url参数

  62. </>复制代码

    1. function getQueryString(key){
    2. var reg = new RegExp("(^|&)"+key+"=([^&]*)(&|$)");
    3. var result = window.location.search.substr(1).match(reg);
    4. return result?decodeURIComponent(result[2]):null;
    5. }
    6. function getRequest() {
    7. var url = window.location.search; //获取url中"?"符后的字串
    8. var theRequest = new Object();
    9. if (url.indexOf("?") != -1) {
    10. var str = url.substr(1);
    11. strs = str.split("&");
    12. for(var i = 0; i < strs.length; i ++) {
    13. theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
    14. }
    15. }
    16. return theRequest;
    17. }
  63. 56.过滤

  64. </>复制代码

    1. var array = [
    2. {
    3. "title": 123,
    4. "num": 1,
    5. "type": [{"name": "A", "num": 1}, {"name": "B", "num": 1}, {"name": "C", "num": 0}]
    6. }, {
    7. "title": 321,
    8. "num": 1,
    9. "type": [{"name": "D", "num": 0}, {"name": "E", "num": 1}, {"name": "F", "num": 0}]
    10. }];
    11. array.forEach(function (x) {
    12. x.type = x.type.filter(function (y) {
    13. return y.num != 0;
    14. });
    15. });
  65. 57.随机生成-50到50之间的不包括0的整数

  66. </>复制代码

    1. function my_rand(){
    2. $num = mt_rand(1, 50);
    3. $rand = mt_rand(1, 10);
    4. return $rand > 4 ? $num : -$num;//控制生成正负数的比例为4:6
    5. }
  67. 58.时间对比

  68. </>复制代码

    1. function compareDate(date1, date2){
    2. var difArr, unitArr;
    3. date1 = new Date(date1);
    4. date2 = new Date(date2);
    5. difArr = [date1.getFullYear() - date2.getFullYear(), date1.getMonth() -date2.getMonth(),date1.getDate() - date2.getDate(),date1.getHours() - date2.getHours(), date1.getMinutes() - date2.getMinutes(),date1.getSeconds() - date2.getSeconds()];
    6. unitArr = ["年","月","日","时","分","秒"]
    7. for(var i = 0; i < 6;i++){
    8. if(difArr[i] !== 0){
    9. return Math.abs(difArr[i]) + unitArr[i];
    10. }
    11. }
    12. }
  69. 59.数组去重

  70. </>复制代码

    1. //传入数组
    2. function unique(arr){
    3. var tmpArr = [];
    4. for(var i=0; i
    5. 60.继承

    6. </>复制代码

      1. /*
      2. * 基类,定义属性
      3. */
      4. function Person(name, age) {
      5. this.name = name;
      6. this.age = age;
      7. }
      8. /*
      9. * 基类,定义方法
      10. */
      11. Person.prototype.selfIntroduce = function () {
      12. console.log("name: " + this.name);
      13. console.log("age: " + this.age);
      14. }
      15. /*
      16. * 子类,定义子类的属性
      17. */
      18. function Student(name, age, school) {
      19. // 调用基类的构造函数
      20. Person.call(this, name, age);
      21. this.school = school;
      22. }
      23. // 使子类继承基类
      24. Student.prototype = new Person();
      25. /*
      26. * 定义子类的方法
      27. */
      28. Student.prototype.goToSchool = function() {
      29. // some code..
      30. }
      31. /*
      32. * 扩展并调用了超类的方法
      33. */
      34. Student.prototype.selfIntroduce = function () {
      35. Student.prototype.__proto__.selfIntroduce.call(this);
      36. console.log("school: " + this.school);
      37. }
      38. var student = new Student("John", 22, "My School");
      39. student.selfIntroduce();
    7. 61.UnicodeUtf-8编码的互相转换

    8. </>复制代码

      1. /**
      2. * utf8字符转换成Unicode字符
      3. * @param [type] $utf8_str Utf-8字符
      4. * @return [type] Unicode字符
      5. */
      6. function utf8_str_to_unicode($utf8_str) {
      7. $unicode = 0;
      8. $unicode = (ord($utf8_str[0]) & 0x1F) << 12;
      9. $unicode |= (ord($utf8_str[1]) & 0x3F) << 6;
      10. $unicode |= (ord($utf8_str[2]) & 0x3F);
      11. return dechex($unicode);
      12. }
      13. /**
      14. * Unicode字符转换成utf8字符
      15. * @param [type] $unicode_str Unicode字符
      16. * @return [type] Utf-8字符
      17. */
      18. function unicode_to_utf8($unicode_str) {
      19. $utf8_str = "";
      20. $code = intval(hexdec($unicode_str));
      21. //这里注意转换出来的code一定得是整形,这样才会正确的按位操作
      22. $ord_1 = decbin(0xe0 | ($code >> 12));
      23. $ord_2 = decbin(0x80 | (($code >> 6) & 0x3f));
      24. $ord_3 = decbin(0x80 | ($code & 0x3f));
      25. $utf8_str = chr(bindec($ord_1)) . chr(bindec($ord_2)) . chr(bindec($ord_3));
      26. return $utf8_str;
      27. }
    9. 62.gzip编码

    10. </>复制代码

      1. function curl_get($url, $gzip=false){
      2. $curl = curl_init($url);
      3. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
      4. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
      5. if($gzip) curl_setopt($curl, CURLOPT_ENCODING, "gzip"); // 关键在这里
      6. $content = curl_exec($curl);
      7. curl_close($curl);
      8. return $content;
      9. }
      10. $url = "http://api.stackexchange.com/2.2/tags?order=asc&sort=popular&site=stackoverflow&tag=qt";
      11. //$data = file_get_contents("compress.zlib://".$url);
    11. 63.Python中文时间

    12. </>复制代码

      1. #!/usr/bin/env
      2. # -*- coding: utf-8 -*-
      3. from datetime import datetime
      4. nt=datetime.now()
      5. print(nt.strftime("%Y年%m月%d日 %H时%M分%S秒").decode("utf-8"))#2015年08月10日 11时25分04秒
      6. print(nt.strftime("%Y{y}%m{m}%d{d}").format(y="年", m="月", d="日"))
    13. 64.list分组,按照下标顺序分成3组:[3, 8, 9] [4, 1, 10] [6, 7, 2, 5]

    14. </>复制代码

      1. a=[1,2,3,4,5,6,7,8,9,10]
      2. [a[i:i+3] for i in xrange(0,len(a),3)]
    15. 64.curl上传文件

    16. </>复制代码

      1. $ch = curl_init();
      2. $data = array("name" => "Foo", "file" => "@/home/vagrant/test.png");
      3. curl_setopt($ch, CURLOPT_URL, "http://localhost/test/curl/load_file.php");
      4. curl_setopt($ch, CURLOPT_POST, 1);
      5. curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); // 5.6 给改成 true了, 弄回去
      6. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      7. curl_exec($ch);
    17. 65.IP地址转换为整数型

    18. </>复制代码

      1. $ipArr = explode(".",$_SERVER["REMOTE_ADDR"]);
      2. $ip = $ipArr[0] * 0x1000000
      3. + $ipArr[1] * 0x10000
      4. + $ipArr[2] * 0x100
      5. + $ipArr[3];
      6. //数字型的IP转为字符型:
      7. $ipVal = $row["client_IP"];
      8. $ipArr = array(
      9. 0 => floor( $ipVal / 0x1000000) );
      10. $ipVint = $ipVal-($ipArr[0]*0x1000000); // for clarity
      11. $ipArr[1] = ($ipVint & 0xFF0000) >> 16;
      12. $ipArr[2] = ($ipVint & 0xFF00 ) >> 8;
      13. $ipArr[3] = $ipVint & 0xFF;
      14. $ipDotted = implode(".", $ipArr);
    19. 66.保存base64图片

    20. </>复制代码

      1. $base64_url = "data:image/jpeg;base64,xxxxxxxxxxxxxxxxxxxxxx";
      2. $base64_body = substr(strstr($base64_url,","),1);
      3. $data= base64_decode($base64_body );
      4. //存储or创建图片:
      5. file_put_contents($file_path,$data);
      6. $image = imagecreatefromstring($data);
      7. $size = getimagesizefromstring ( $data);var_dump($size);
      8. //读取图片文件,转换成base64编码格式
      9. $image_file = "test.jpg";
      10. $image_info = getimagesize($image_file);
      11. $base64_image_content = "data:{$image_info["mime"]};base64," . chunk_split(base64_encode(file_get_contents($image_file)));
      12. //保存base64字符串为图片
      13. //匹配出图片的格式
      14. if (preg_match("/^(data:s*image/(w+);base64,)/", $base64_image_content, $result)){
      15. $type = $result[2];
      16. $new_file = "./test.{$type}";
      17. if (file_put_contents($new_file, base64_decode(str_replace($result[1], "", $base64_image_content)))){
      18. echo "新文件保存成功:", $new_file;
      19. }
      20. }
      21. ?>
    21. 67.日志记录print_r( $value, true )

    22. </>复制代码

      1. /**
      2. 错误日志类
      3. */
      4. class C_Log
      5. {
      6. /**
      7. 日志保存目录
      8. @var string
      9. */
      10. private $path = "";
      11. /**
      12. 只能运行一个实例
      13. @var [type]
      14. */
      15. private static $instance;
      16. /**
      17. 构造函数
      18. 初始化日志文件地址
      19. */
      20. function __construct($path)
      21. {
      22. $this->path = $path;
      23. }
      24. public function logPrint($name,$value)
      25. {
      26. //获取时间
      27. $_o = date("Y-m-d H:m:s",time())."
      28. ";
      29. $_o .= "==". $name . "==";
      30. //打印内容
      31. if( is_array( $value ) || is_object( $value ) ){
      32. $_o .= print_r( $value, true ). "
      33. ";
      34. } else {
      35. $_o .= $value. "
      36. ";
      37. }
      38. //输出到文件
      39. $this->_log($_o);
      40. }
      41. /**fdf
      42. 打印日志
      43. @return [type] [description]
      44. */
      45. private function _log($log){
      46. error_log($log,3,$this->path);
      47. }
      48. /**
      49. 输出日志
      50. @return [type] [description]
      51. */
      52. public static function log($name, $value)
      53. {
      54. if (empty(self::$instance)) {
      55. self::$instance = new C_Log(__DIR__."/error_log.log");
      56. }
      57. self::$instance->logPrint($name, $value);
      58. }
      59. }
    23. 68.过滤子类

    24. </>复制代码

      1. function getByClass(parent, classname) {
      2. var tags = parent.getElementsByTagName("*");
      3. return [].filter.call(tags, function(t) {
      4. return t.classList.contains(classname);
      5. });
      6. }
      7. //
      8. function getByClass(parent, classname) {
      9. return parent.querySelectorAll("." + classname);
      10. }
    25. 69.JSON.stringify

    26. </>复制代码

      1. function setProp(obj) {
      2. for (var p in obj) {
      3. switch (typeof (obj[p])) {
      4. case "object":
      5. setProp(obj[p]);
      6. break;
      7. case "undefined":
      8. obj[p] = "";
      9. break;
      10. }
      11. }
      12. return obj;
      13. }
      14. JSON.stringify(setProp({ a: 1, b: 2, c: undefined }));//{"a":1,"b":2,"c":""}
    27. 70.判断用户的IP是否局域网IP

    28. </>复制代码

      1. function is_local_ip($ip_addr = null) {
      2. if (is_null($ip_addr)) {
      3. $ip_addr = $_SERVER["REMOTE_ADDR"];
      4. }
      5. $ip = ip2long($ip_addr);
      6. return $ip & 0xffff0000 == 0xc0a80000 // 192.168.0.0/16
      7. || $ip & 0xfff00000 == 0xac100000 // 172.16.0.0/12
      8. || $ip & 0xff000000 == 0xa0000000 // 10.0.0.0/8
      9. || $ip & 0xff000000 == 0x7f000000 // 127.0.0.0/8
      10. ;
      11. }
    29. 71.遍历出当月的所有日子和星期

    30. </>复制代码

      1. var d = new Date(); // 这是当天
      2. d.setDate(1); // 这就是1号
      3. var weekday = d.getDay(); // 1号星期几,从星期天为0开始
      4. d.setMonth(d.getMonth() + 1);
      5. d.setDate(0); // 这两句得到最当月最后一天
      6. var end = d.getDate(); // 最后一天的日,比如8月就是31
      7. var days = [];
      8. for (var i = 0; i < end; i++) {
      9. days[i] = {
      10. day: i + 1,
      11. week: (weekday + i) % 7
      12. }
      13. }
      14. console.log(days);
    31. 72.Downloading Data From localStorage

    32. </>复制代码

      1. var myData = {
      2. "a": "a",
      3. "b": "b",
      4. "c": "c"
      5. };
      6. // add it to our localstorage
      7. localStorage.setItem("data", JSON.stringify(myData));
      8. // encode the data into base64
      9. base64 = window.btoa(localStorage.getItem("data"));
      10. // create an a tag
      11. var a = document.createElement("a");
      12. a.href = "data:application/octet-stream;base64," + base64;
      13. a.innerHTML = "Download";
      14. // add to the body
      15. document.body.appendChild(a);
    33. 73."数据类型"判断函数

    34. </>复制代码

      1. function datatypeof(arg){
      2. return Object.prototype.toString.call(arg).match(/[objects(w+)]/)[1];
      3. }
    35. 74.二维数组去除重复,重复值相加

    36. </>复制代码

      1. $arr = array(
      2. array("id" => 123, "name" => "张三", "amount"=>"1"),
      3. array("id" => 123, "name" => "李四", "amount" => "1"),
      4. array("id" => 124, "name" => "王五", "amount" => "1"),
      5. array("id" => 125, "name" => "赵六", "amount" => "1"),
      6. array("id" => 126, "name" => "赵六", "amount" => "2"),
      7. array("id" => 126, "name" => "赵六", "amount" => "2")
      8. );
      9. $new = array();
      10. foreach($arr as $row){
      11. if(isset($new[$row["name"]])){
      12. $new[$row["name"]]["amount"] += $row["amount"];
      13. }else{
      14. $new[$row["name"]] = $row;
      15. }
      16. }
    37. 75.含有从属关系的元素重新排列

    38. </>复制代码

      1. $arr = array(
      2. array("id"=>21, "pid"=>0, "name"=>"aaa"),
      3. array("id"=>22, "pid"=>0, "name"=>"bbb"),
      4. array("id"=>23, "pid"=>0, "name"=>"ccc"),
      5. array("id"=>24, "pid"=>23, "name"=>"ffffd"),
      6. array("id"=>25, "pid"=>23, "name"=>"eee"),
      7. array("id"=>26, "pid"=>22, "name"=>"fff"),
      8. );
      9. $temp=[];
      10. foreach ($arr as $item)
      11. {
      12. list($id,$pid,$name) = array_values($item); // 取出数组的值并分别生成变量
      13. if(array_key_exists($pid, $temp))
      14. // 检查临时数组$temp中是否存在键名与$pid的值相同的键
      15. {
      16. $temp[$pid]["child"][]=array("id"=>$id,"pid"=>$pid,"name"=>$name);
      17. // 如果存在则新增数组至临时数组中键名为 $pid 的子元素 child 内
      18. }else
      19. $temp[$id]=array("id"=>$id,"pid"=>$pid,"name"=>$name);
      20. // 如果不存在则新增数组至临时数组中并设定键名为 $id
      21. }
      22. $array = array_values($temp);
      23. // 将临时数组中以 $id 为键名的键修改为数字索引
      24. echo "

        </>复制代码

        1. ";
        2. print_r($array);
        3. //or
        4. foreach ($arr as $item)
        5. {
        6. if (array_key_exists($item["pid"], $temp))
        7. {
        8. $temp[$item["pid"]]["child"][]=$item;
        9. }else
        10. $temp[$item["id"]]=$item;
        11. }
      25. 76.随机中文字符

      26. </>复制代码

        1. //正则表达式匹配中文[u4e00-u9fa5]
        2. //parseInt("4E00",16) 19968 parseInt("9FA5",16);20901
        3. var randomHz=function(){
        4. eval( "var word=" + ""u" + (Math.round(Math.random() * 20901) + 19968).toString(16)+""");
        5. return word;
        6. }
        7. for(i=0;i<100;i++){
        8. console.log(randomHz());
        9. }
      27. 77.jQuery解析url

      28. </>复制代码

        1. $(document).ready(function () {
        2. var url = "http://iwjw.com/codes/code-repository?id=12#top";
        3. var a = $("", { href: url});
        4. var sResult = "Protocol: " + a.prop("protocol") + "
          " + "Host name: " + a.prop("hostname") + "
          "
        5. + "Path: " + a.prop("pathname") + "
          "
        6. + "Query: " + a.prop("search") + "
          "
        7. + "Hash: " + a.prop("hash");
        8. $("span").html(sResult);
        9. });
      29. 78.用JS实现一个数组合并的方法(要求去重)

      30. 复制代码 复制代码

        1. var arr1 = ["a"];
        2. var arr2 = ["b", "c"];
        3. var arr3 = ["c", ["d"], "e", undefined, null];
        4. var concat = (function(){
        5. // concat arr1 and arr2 without duplication.
        6. var concat_ = function(arr1, arr2) {
        7. for (var i=arr2.length-1;i>=0;i--) {
        8. arr1.indexOf(arr2[i]) === -1 ? arr1.push(arr2[i]) : 0;
        9. }
        10. };
        11. // concat arbitrary arrays.
        12. // Instead of alter supplied arrays, return a new one.
        13. return function(arr) {
        14. var result = arr.slice();
        15. for (var i=arguments.length-1;i>=1;i--) {
        16. concat_(result, arguments[i]);
        17. }
        18. return result;
        19. };
        20. }());
        21. 执行:concat(arr1, arr2, arr3)
        22. 返回:[ "a", null, undefined, "e", [ "d" ], "c", "b" ]
        23. var merge = function() {
        24. return Array.prototype.concat.apply([], arguments)
        25. }
        26. merge([1,2,4],[3,4],[5,6]);
        27. //[1, 2, 4, 3, 4, 5, 6]
      31. 79.字节转化

      32. </>复制代码

        1. function convert($size)
        2. {
        3. $unit = array("b", "kb", "mb", "gb", "tb", "pb");
        4. return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . " " . $unit[$i];
        5. }
        6. echo convert(memory_get_usage());
        7. function cacheMem($key)
        8. {
        9. static $mem = null;
        10. if ($mem === null) {
        11. $mem = new Memcache();
        12. $mem->connect("127.0.0.1", 11211);
        13. }
        14. $data = $mem->get($key);
        15. if (empty($data)) {
        16. $data = date("Y-m-d H:i:s");
        17. $mem->set($key, $data);
        18. }
        19. return $data;
        20. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/37561.html

相关文章

  • 【数据科学系统学习】机器学习算法 # 西瓜书学习记录 [10] 决策树实践

    摘要:本篇内容为机器学习实战第章决策树部分程序清单。适用数据类型数值型和标称型在构造决策树时,我们需要解决的第一个问题就是,当前数据集上哪个特征在划分数据分类时起决定性作用。下面我们会介绍如何将上述实现的函数功能放在一起,构建决策树。 本篇内容为《机器学习实战》第 3 章决策树部分程序清单。所用代码为 python3。 决策树优点:计算复杂度不高,输出结果易于理解,对中间值的缺失不敏感,可...

    suemi 评论0 收藏0
  • 何恺明团队推出Mask^X R-CNN,将实例分割扩展到3000类

    摘要:从标题上可以看出,这是一篇在实例分割问题中研究扩展分割物体类别数量的论文。试验结果表明,这个扩展可以改进基准和权重传递方法。 今年10月,何恺明的论文Mask R-CNN摘下ICCV 2017的较佳论文奖(Best Paper Award),如今,何恺明团队在Mask R-CNN的基础上更近一步,推出了(以下称Mask^X R-CNN)。这篇论文的第一作者是伯克利大学的在读博士生胡戎航(清华...

    MockingBird 评论0 收藏0
  • 决策树的Python实现(含代码)

    摘要:也就是说,决策树有两种分类树和回归树。我们可以把决策树看作是一个规则的集合。这样可以提高决策树学习的效率。解决这个问题的办法是考虑决策树的复杂度,对已生成的决策树进行简化,也就是常说的剪枝处理。最后得到一个决策树。 一天,小迪与小西想养一只宠物。 小西:小迪小迪,好想养一只宠物呀,但是不知道养那种宠物比较合适。 小迪:好呀,养只宠物会给我们的生活带来很多乐趣呢。不过养什么宠物可要考虑好...

    yanest 评论0 收藏0
  • 如何用机器学习算法来进行电影分类?(含Python代码)

    摘要:电影分析近邻算法周末,小迪与女朋友小西走出电影院,回味着刚刚看过的电影。近邻分类电影类型小迪回到家,打开电脑,想实现一个分类电影的案例。分类器并不会得到百分百正确的结果,我们可以使用很多种方法来验证分类器的准确率。 电影分析——K近邻算法 周末,小迪与女朋友小西走出电影院,回味着刚刚看过的电影。 小迪:刚刚的电影很精彩,打斗场景非常真实,又是一部优秀的动作片! 小西:是吗?我怎么感觉这...

    animabear 评论0 收藏0

发表评论

0条评论

marser

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<