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)
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);}
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['name'].'<br>'; if(isset($t['son'])){ getTreeData($t['son']); } }}
4.數組排序 a - b 是數字數組寫法 遇到字串的時候就要
var test = ['ab', 'ac', 'bd', 'bc'];test.sort(function(a, b) { if(a < b) { return -1; } if(a > b) { return 1; } return 0;});
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]
6.array_map 閉包中只接受一個或者多個參數,閉包的參數數量和 array_map 本身的參數數量必須一致
$input = ['key' => 'value'];array_map(function($key, $value) { echo $key . $value;}, array_keys($input), $input)// 'keyvalue'$double = function($item) { return 2 * $item;}$result = array_map($double, [1,2,3]);// 2 4 6
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/>"; }
8 .datetime
function getCurMonthFirstDay($date){ return date('Y-m-01', strtotime($date));} getCurMonthLastDay('2015-07-23')function getCurMonthLastDay($date){ return date('Y-m-d', strtotime(date('Y-m-01', strtotime($date)) . ' +1 month -1 day'));}
9.加密解密
function encrypt($data, $key){ $key = md5($key); $x = 0; $len = strlen($data); $l = strlen($key); $char = ''; for ($i = 0; $i < $len; $i++) { if ($x == $l) { $x = 0; } $char .= $key{$x}; $x++; } $str = ''; 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 = ''; for ($i = 0; $i < $len; $i++) { if ($x == $l) { $x = 0; } $char .= substr($key, $x, 1); $x++; } $str = ''; 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;}
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('JSON_UNESCAPED_UNICODE')){ 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('UCS-2', 'UTF-8', pack('H4', '\\1'))", "\\1"), json_encode($result) ); }}
12.二維數組去重
$arr = array( array('id'=>'2','title'=>'...','ding'=>'1','jing'=>'1','time'=>'...','url'=>'...','dj'=>'...'), array('id'=>'2','title'=>'...','ding'=>'1','jing'=>'1','time'=>'...','url'=>'...','dj'=>'...'));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; }
13.格式化位元組大小
/*** 格式化位元組大小* @param number $size 位元組數* @param string $delimiter 數字和單位分隔字元* @return string 格式化後的帶單位的大小* @author */function format_bytes($size, $delimiter = '') { $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); for ($i = 0; $size >= 1024 && $i < 6; $i++) $size /= 1024; return round($size, 2) . $delimiter . $units[$i];}
14.3分鐘前
/*** 將指定時間戳記轉換為截止當前的xx時間前的格式 例如 return '3分鐘前''* @param string|int $timestamp unix時間戳記* @return string*/function time_ago($timestamp) { $etime = time() - $timestamp; if ($etime < 1) return '剛剛'; $interval = array ( 12 * 30 * 24 * 60 * 60 => '年前 ('.date('Y-m-d', $timestamp).')', 30 * 24 * 60 * 60 => '個月前 ('.date('m-d', $timestamp).')', 7 * 24 * 60 * 60 => '周前 ('.date('m-d', $timestamp).')', 24 * 60 * 60 => '天前', 60 * 60 => '小時前', 60 => '分鐘前', 1 => '秒前' ); foreach ($interval as $secs => $str) { $d = $etime / $secs; if ($d >= 1) { $r = round($d); return $r . $str; } };}
15.社會安全號碼
/*** 判斷參數字串是否為天朝社會安全號碼* @param $id 需要被判斷的字串或數字* @return mixed false 或 array[有內容的array boolean為真]*/function is_citizen_id($id) { //長度效驗 18位身份證中的X為大寫 $id = strtoupper($id); if(!(preg_match('/^\d{17}(\d|X)$/',$id) || preg_match('/^\d{15}$/',$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('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'); $cardNoSum = 0; if(strlen($id)==16) { $id = substr(0, 6).'19'.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?'男':'女'; //地區驗證 if(is_null($oCity[$City])) {return false;} //出生日期效驗 if($BirthYear>2078 || $BirthYear<1900) {return false;} $RealDate = strtotime($BirthYear.'-'.$BirthMonth.'-'.$BirthDay); if(date('Y',$RealDate)!=$BirthYear || date('m',$RealDate)!=$BirthMonth || date('d',$RealDate)!=$BirthDay) { return false; } return array('id'=>$id,'location'=>$oCity[$City],'Y'=>$BirthYear,'m'=>$BirthMonth,'d'=>$BirthDay,'sex'=>$Sex);}
16.擷取二維數組中某個key的集合
$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', ), ...... );$ids = array(); $ids = array_map('array_shift', $user);$ids = array_column($user, 'id');//php5.5$names = array(); $names = array_reduce($user, create_function('$v,$w', '$v[$w["id"]]=$w["name"];return $v;'));
以上所述就是本文的全部內容了,希望大家能夠喜歡。