array_walk - 对数组的每个元素应用自定义函数
array_walk ( array &$array , callable $callback [, mixed $userdata = null ] ) : bool
回调函数的参数,第一个是元素值,第二个是元素键名,第三个是可选的 $userdata
。
如果只想改变数组值,第一个参数可使用引用传递,即在参数前加上 &
。
<?php $fruits = array("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 ...: a. orange b. banana c. apple ... and after: a. fruit: orange b. fruit: banana c. fruit: apple
上面说如果想改变数组的值,必须使用引用传递,于是我想能不能不这样,直接使用返回值,测试了一下,是不行的,因为回调函数的返回值并没有用到,猜想此函数的目的主要在把数组的每个元素遍历一下,即 走 walk
一遍.
如对本文有疑问, 点击进行留言回复!!
20.7.17 笔记算数运算符 复合运算符重载 比较运算重载 多态 设计原则 类的单一职责 依赖倒置 组合复用原则 里氏替换 迪米特法则 矩阵转置原理
网友评论