您的位置:首页 > 编程语言 > PHP开发

php学习笔记之array_walk函数

2014-04-06 21:26 120 查看
4000

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

<?php
function 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 Cat
The key b has the value Dog
The key c has the value Horse


例子 2

带有一个参数:

<?php
function 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 Cat
b has the value Dog
c has the value Horse


例子 3

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

<?php
function 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 )
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php array_walk