精易论坛

标题: PHP- 四个数组回调函数 [打印本页]

作者: dream518    时间: 2020-7-16 11:56
标题: PHP- 四个数组回调函数

1 array_filter 用回调函数过滤数组中的单元



## array_filter
// 返回数组中后缀名为.jpg 的图片
$image = ['web.png','name.gif','item.jpg','kk.pgf','vv.jpg'];
$image = array_filter($image,function($arr){
    return  pathinfo($arr)['extension'] === 'jpg';
});
print_r($image);
// 输出  Array ( [zxsq-anti-bbcode-2] => item.jpg [zxsq-anti-bbcode-4] => vv.jpg )
// 索引进行重排
sort($image);
print_r($image);
// 输出 Array ( [zxsq-anti-bbcode-0] => item.jpg [zxsq-anti-bbcode-1] => vv.jpg )

2 arrtay_map 为数组的每个元素应用回调函数进行处理,返回新数组



## array_map
// 将数组进行拉平
$res = [[1,2,3],1,2,(new class{public $name='中国'; public $gps='亚洲';})];
// printf('<pre>%s</pre>',print_r($res,true));
$arr = array_map(function($item){
switch (gettype($item)) {
    case 'object':
        $item = get_object_vars($item);
        case 'array':
        $item =implode(',',$item);

}
return $item;
},$res);

printf('<pre>%s</pre>',print_r($arr,true));
// 输出 Array
// (
//     [zxsq-anti-bbcode-0] => 1,2,3
//     [zxsq-anti-bbcode-1] => 1
//     [zxsq-anti-bbcode-2] => 2
//     [zxsq-anti-bbcode-3] => 中国,亚洲
// )

3 array_work 使用用户自定义函数对数组中的每个元素做回调处理


// array_walk()
$res =['id'=>'101','name'=>'machael','age'=>'15'];
array_walk($res,function($item,$key){
echo $key .' = '.$item .'<br>';
});

// 输出
// id = 101
// name = machael
// age = 15

4 array_reduce 发送数组中的值到用户自定义函数,并返回一个字符串


## array_reduce

$arr = null;
$arr[] = ['id'=>'101','name'=>'machael','age'=>'15'];
$arr[] = ['id'=>'102','name'=>'mach','age'=>'16'];
$arr[] = ['id'=>'103','name'=>'maael','age'=>'18'];
// printf('<pre>%s</pre>',print_r($arr,true))
// 获取当期二维数组中每个id的值
$arr = array_reduce($arr,function($res,$item){
return $res.','.$item['id'];
});
printf('<pre>%s</pre>',print_r($arr,true));
//输出结果  ,101,102,103

// 求和
$num = [1,2,3,4];
$sum = array_reduce($num,function($a,$b){
    return $a + $b;
});
printf('<pre>%s</pre>',print_r($sum,true));
// 输出结果 10

// 合并两个数组
$a = ['name','id','password'];
$b = ['machiel','101','123456'];
// 合并
$res = array_map(function($arr_a,$arr_b){
    return [$arr_a => $arr_b];
},$a,$b);
// 二维转一维
$res = array_reduce($res,function($arr,$item){
    $key = key($item);
    $current = current($item);
    $arr[$key] = $current;
    return $arr;
});

printf('<pre>%s</pre>',print_r($res,true));
// 输出 Array
// (
//     [zxsq-anti-bbcode-name] => machiel
//     [zxsq-anti-bbcode-id] => 101
//     [zxsq-anti-bbcode-password] => 123456
// )






欢迎光临 精易论坛 (https://125.confly.eu.org/) Powered by Discuz! X3.4