Rumah > Artikel > pembangunan bahagian belakang > php函数集
php$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. 循环删除目录
phpfunction 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.无限极分类生成树
php<br />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 是数字数组写法 遇到字符串的时候就要
phpvar test = ['ab', 'ac', 'bd', 'bc'];test.sort(function(a, b) { if(a < b) { return -1; } if(a > b) { return 1; } return 0;});
php$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 本身的参数数量必须一致
php$input = ['key' => 'value'];array_map(function($key, $value) { echo $key . $value;}, array_keys($input), $input)// 'keyvalue'
7.繁殖兔子
php$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
phpfunction 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'));}