php学习笔记之array_walk函数

来源:互联网 发布:java抽象类的作用 编辑:程序博客网 时间:2024/05/20 07:58

array_walk();对数组中的每个成员应用用户自定义函数(或者叫回调函数)。


语法:

bool array_walk(array &$array,callable $funcname [,mixed $userdata = null ]),这样,会将用户自定义函数应用到array数组的每个单元

array_walk()不会受到array没不数组指针的影响,会便利整个数组而不管指针的位置。


参数:

array 数组,

funcname 用户自定义函数,它接收连个参数,array的值作为地一个,键名作为第二个。


返回值:

success -> true; failure -> false。


注意:

1、用户不能在funcname中改变数组本身的结构,只有array的值才可以被改变,例如增加/删除单元,unset 单元等等。如果array_walk() 作用的数组改变了,则此函数的的行为未经定义,且不可预期。

2、如果 funcname 需要直接作用于数组中的值,则给 funcname 的第一个参数指定为引用。这样任何对这些单元的改变也将会改变原始数组本身。


例子 1

<?phpfunction myfunction($value,$key) {echo "The key $key has the value $value<br />";}$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");array_walk($a,"myfunction");?>

输出:

The key a has the value CatThe key b has the value DogThe key c has the value Horse

例子 2

带有一个参数:

<?phpfunction myfunction($value,$key,$p) {echo "$key $p $value<br />";}$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");array_walk($a,"myfunction","has the value");?>

输出:

a has the value Catb has the value Dogc has the value Horse

例子 3

改变数组元素的值(请注意 &$value):

<?phpfunction myfunction(&$value,$key) {$value="Bird;}$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");array_walk($a,"myfunction");print_r($a);?>

输出:

Array ( [a] => Bird [b] => Bird [c] => Bird )




0 0
原创粉丝点击