Blogger Information
Blog 57
fans 0
comment 0
visits 46967
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
数组的回调处理将一个函数做为参数进行传递
藍錄的博客
Original
565 people have browsed it

实例

<?php
/**
 * 数组的回调处理
 * 将一个函数做为参数进行传递
 * 1. array_filter($arr, $callback)
 * 2. array_walk($arr, $callback())
 */

//1. array_filter():回调处理数组中的每个元素的值,仅返回结果为true的元素
$arr1 = [5,0,'',20,null,88,false,'php'];
echo '<pre>';
//echo '原始数组',var_export($arr1,true),',共有:',count($arr1),'个元素<hr>';
// ''空字符串,0,null,false: false
$arr2 = array_filter($arr1);
//echo '新数组',var_export($arr2,true),',共有:',count($arr2),'个元素<hr>';
//非常适合删除数组中的空元素
//传入一个回调: 匿名函数
$arr3 = ['html','css','javascript'];
$arr4 =array_filter($arr3, function ($value){
    return $value !== 'css';
});
//echo var_export($arr4),'<hr>';

//2. array_walk():对数组中每个元素的键和值进行处理
$arr = ['name'=>'admin','email'=>'admin@php.cn'];
echo var_export($arr, true), '<hr>';
//格式化
array_walk($arr, function (&$value, $key) {
    echo $key,':',$value,'<br>';
});
echo '<hr>';
// 回调的第三个参数的用法

array_walk($arr, function (&$value, $key, $name) {
    //如果当前的用户名是:admin,则授权查看,否则拒绝
    if ($value != $name) {
        exit('无权查看');
    } else {
        exit($key.':'.$value);
    }

},'admin1');
echo '<hr>';
echo '<pre>';
//echo var_export(array_unique([1,2,2,3,3,4,4,5,6]));
//echo var_export(array_fill(0,10,0));
//echo var_export(array_rand(range(1,33),7));
//echo var_export(array_rand(range(1,16),3));
$arr = ['东邪','西毒','南帝','北丐'];
shuffle($arr);  // 验证码
echo var_export($arr);
//array_merge():合并多个数组,相同键名互相覆盖
$db_sys = ['host'=>'127.0.0.1','user'=>'root','pass'=>'root'];
$db_user = ['host'=>'localhost', 'pass'=>sha1('123456')];
$res=array_merge($db_sys, $db_user);
echo var_export($res);

运行实例 »

点击 "运行实例" 按钮查看在线实例

 

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post