实例
1.对数组中的每个元素应用用户自定义函数:
<?php
function myfunction($value,$key)
{
echo "The key $key has the value $value<br>";
}
$a=array("a"=>"red","b"=>"green","c"=>"blue");
array_walk($a,"myfunction");
?>
输出
The key a has the value red
The key b has the value green
The key c has the value blue
2.带有一个参数:
<?php
function myfunction($value,$key,$p)
{
echo "$key $p $value<br>";
}
$a=array("a"=>"red","b"=>"green","c"=>"blue");
array_walk($a,"myfunction","has the value");
?>
输出
a has the value red
b has the value green
c has the value blue
3.改变数组元素的值(请注意 &$value):
<?php
function myfunction(&$value,$key)
{
$value="yellow";
}
$a=array("a"=>"red","b"=>"green","c"=>"blue");
array_walk($a,"myfunction");
print_r($a);
?>
输出
Array
(
[a] => yellow
[b] => yellow
[c] => yellow
)
定义和用法
array_walk() 函数对数组中的每个元素应用用户自定义函数。在函数中,数组的键名和键值是参数。
提示:如需操作更深的数组(一个数组中包含另一个数组),请使用 array_walk_recursive() 函数。
语法
array_walk(array,myfunction,parameter...)
参数 | 描述 |
---|---|
array | 必需。规定数组。 |
myfunction | 必需。用户自定义函数的名称。 |
parameter,... | 可选。规定用户自定义函数的参数,您可以为函数设置一个或多个参数。 |