php的array_walk,PHP array_walk() 函数详解
定義
array_walk - 對數組的每個元素應用自定義函數
描述
array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] ) : bool
回調函數的參數,第一個是元素值,第二個是元素鍵名,第三個是可選的 $userdata。
如果只想改變數組值,第一個參數可使用引用傳遞,即在參數前加上 &。
示例
$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
\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 一遍.
總結
以上是生活随笔為你收集整理的php的array_walk,PHP array_walk() 函数详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: kafka 创建topic_Kafka试
- 下一篇: 动态规划算法php,php算法学习之动态