php数组(十) array_walk
array_walk — 使用用户自定义函数对数组中的每个元素做回调处理
将用户自定义函数 funcname 应用到 array 数组中的每个单元。
array_walk() 不会受到 array 内部数组指针的影响。array_walk() 会遍历整个数组而不管指针的位置。
参数
array
- 输入的数组。
callback
- 典型情况下
callback接受两个参数。array参数的值作为第一个,键名作为第二个。
注意:
- 如果
callback需要直接作用于数组中的值,则给callback的第一个参数指定为引用。这样任何对这些单元的改变也将会改变原始数组本身。
注意:
- 参数数量超过预期,传入内置函数 (例如 strtolower()), 将抛出警告,所以不适合当做
funcname。
- 只有
array的值才可以被改变,用户不应在回调函数中改变该数组本身的结构。例如增加/删除单元,unset 单元等等。如果 array_walk() 作用的数组改变了,则此函数的的行为未经定义,且不可预期。
userdata
- 如果提供了可选参数
userdata,将被作为第三个参数传递给 callbackfuncname。
1、遍历数组示例
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function test_print($item2, $key)
{
echo "$key. $item2<br />\n";
}
array_walk($fruits, 'test_print');
?>
输出:遍历输出二维数组的每一个元素
d. lemon<br /> a. orange<br /> b. banana<br /> c. apple<br />
2、使用第三个参数可以传入参数,并可以在回调函数中使用&符号改变数组的值
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function test_alter(&$item1, $key, $prefix)
{
$item1 = "$prefix: $item1";
}
function test_print($item2, $key)
{
echo "$key. $item2<br />\n";
}
echo "Before ...:\n";
array_walk($fruits, 'test_print');
array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";
array_walk($fruits, 'test_print');
?>
输出:
Before ...: d. lemon<br /> a. orange<br /> b. banana<br /> c. apple<br /> ... and after: d. fruit: lemon<br /> a. fruit: orange<br /> b. fruit: banana<br /> c. fruit: apple<br />
3、不可以在回调函数中改变数组结构,例如想删除key等于a元素,会删除失败
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function test_alter(&$item1, $key, &$fruits)
{
if($key == 'a'){
unset($fruits[$key]);
}
}
function test_print($item2, $key)
{
echo "$key. $item2<br />\n";
}
echo "... and before:\n";
array_walk($fruits, 'test_print');
array_walk($fruits, 'test_alter', $fruits);
echo "... and after:\n";
array_walk($fruits, 'test_print');
?>
返回:数组结构未发生改变
... and before: d. lemon<br /> a. orange<br /> b. banana<br /> c. apple<br /> ... and after: d. lemon<br /> a. orange<br /> b. banana<br /> c. apple<br />
posted on 2021-08-04 21:01 1450811640 阅读(116) 评论(0) 收藏 举报
浙公网安备 33010602011771号