// 函数式编程
$users = array(
array('id' => 1, 'name' => 'abc1', 'age' => 29, '性别' => '男'),
array('id' => 2, 'name' => 'abc2', 'age' => 21, '性别' => '女'),
array('id' => 3, 'name' => 'abc3', 'age' => 23, '性别' => '男'),
array('id' => 4, 'name' => 'abc4', 'age' => 25, '性别' => '女'),
array('id' => 5, 'name' => 'abc5', 'age' => 20, '性别' => '女'),
array('id' => 6, 'name' => 'abc6', 'age' => 24, '性别' => '男'),
array('id' => 7, 'name' => 'abc7', 'age' => 28, '性别' => '女'),
array('id' => 8, 'name' => 'abc8', 'age' => 27, '性别' => '男'),
);
//获取性别为女的用户
$arrayFilter = array_filter($users, function($item){
return $item['性别'] == '女' ;
});
// 不影响原数组,返回一个新数组
$arrayMap = array_map(function($item){
return array(
'id' => $item['id'],
'name' => $item['name'],
'age' => $item['age'],
'gender' => $item['性别'] == '男' ? 'male' : 'female',
);
}, $users);
// 修改原数组,对年龄+10处理,同时新增索引gender,返回值 1 或 0
array_walk($users, function(&$item, $index){
$item['gender'] = $item['性别'] == '男' ? 'male' : 'female';
if ($index % 2 == 0) {
$item['age'] += 10;
}
});
//array_reduce(array $input , callable $function [,$initial = NULL ]) 用回调函数迭代地将数组简化为单一的值
// 求最大年龄的用户,返回最大年龄用户信息
$arrayReduce = array_reduce($users, function($init, $val){
return $init['age'] > $val['age'] ? $init : $val;
}, array('age' => 0));
// 求平均年龄
$avgAge = array_reduce($users, function($init, $item){
return $init + $item['age'];
}, 0) / count($users);
/*
* array_reduce 的内部实现方式
function array_reduce($data, $callback, $initial) {
foreach ($data as $index => $val) {
$initial = $callback($initial, $val);
}
return $initial;
}
*/
//用array_map和array_mutisort来排序
//利用array_map获取要依据排序的数组,(匿名函数 create_function($args, return $val))
//$arrField = array_map(create_function('$item', 'return $item["age"];'), $users); 【不推荐】
$arrField = array_map(function($item){
return $item['age'];
}, $users);
//利用array_mutisort来进行年龄从大到小排序
$arrSort = array_multisort($arrField, SORT_DESC, $users);
//闭包实现计数器
function counts() {
$a = 1;
// 闭包,引用变量$a
return function() use(&$a) {
return $a++;
};
}
$countFunc = counts();
echo $countFunc(); // 1
echo $countFunc(); // 2
echo $countFunc(); // 3
echo $countFunc(); // 4
搜索
标签
study
ab
amap
apache
apahe
awk
aws
bat
centos
CFS
chrome
cmd
cnpm
composer
consul
crontab
css
curl
cygwin
devops
di
docker
docker,docker-compose
ethereum
excel
fiddler
fluentd
framework
front-end
git
gitgui
github
glide
go
golang
gorm
grafana
gzip
ioc
item2
iterm2
javascript
jenkins
jsonp
kafka
laradock
laravel
larval
linux
liunux
log
mac
mac, wi-fi
macos
magento
mariaDB
minikube
mongoDB
msp
mysql
netbeans
nginx
nodejs
nohup
npm
nsq
oracle
php
php-fpm
php7
phpstorm
php扩展
Protobuf
python
redis
scp
server
shell
soap
socket
socket5
sql
sre
ssdb
ssh
ssl
study
sublime
swift
system
td-agent
uml
v2ray
vagrant
vagrnat
vim
vpn
vue
vue.js
webpack
webrtc
websocket
webtatic
windows
windows7
word
wps
xdebug
yarn
yii2
yum
zookeeper
世界国家
互联网
以太坊
分类
前端
小程序
打印机
排序算法
搞笑
权限
粤语
缓存
网络
虚拟机
视频
设计模式
项目管理
热门文章
友情链接