本文主要是介绍array_walk()使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
bool array_walk ( array
&$array
, callable $callback
[, mixed $userdata
= NULL
] )
将用户自定义函数 funcname 应用到 array 数组中的每个单元。
array_walk() 不会受到 array 内部数组指针的影响。array_walk() 会遍历整个数组而不管指针的位置。
array_walk($array, callback, userdata);
$array 输入的数组, callback($array的参数, 键名,$prefix) $userdata 将被作为第三个参数传递给 callback prefix
测试环境 7.0.1
<?php $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); function test_alter(&$item1, $key, $prefix) //注意这里第一个是取地址符,$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"; var_dump($fruits); array_walk($fruits, 'test_print');
Before ...: d. lemon a. orange b. banana c. apple ... and after: d. fruit: lemon a. fruit: orange b. fruit: banana c. fruit: apple
$fruits = array("1" => "lemon", "2" => "orange", "3" => "banana", "4" => "apple"); function test_print($item2, &$key) {++$key; echo "$key. $item2<br />\n"; }array_walk($fruits, 'test_print'); var_dump($fruits);exit; array(4) { [1]=> string(5) "lemon" [2]=> string(6) "orange" [3]=> string(6) "banana" [4]=> string(5) "apple" }
key值没有变化,说明,array_walk function中第二个方法中如果使用的key取地址符,key的值依然不变
Waring:
If the class is static:
array_walk($array, array('self', 'walkFunction'));
or
array_walk($array, array('className', 'walkFunction'));
Otherwise:
array_walk($array, array($this, 'walkFunction'));
array_walk($array, array('self', 'walkFunction'));
or
array_walk($array, array('className', 'walkFunction'));
Otherwise:
array_walk($array, array($this, 'walkFunction'));
array_walk 与匿名函数结合使用
function zip(&$data, $glue=': ') {if(!is_array($data)) {throw new InvalidArgumentException('First parameter must be an array'); }array_walk($data, function(&$value, $key, $joinUsing) {$value = $key . $joinUsing . $value; }, $glue); }$myName = 'Matthew Purdon'; $myEmail = 'matthew@example.com'; $from = "$myName <$myEmail>"; $headers['From'] = $from; $headers['Reply-To'] = $from; $headers['Return-path'] = "<$myEmail>"; $headers['X-Mailer'] = "PHP" . phpversion() . ""; $headers['Content-Type'] = 'text/plain; charset="UTF-8"'; zip($headers); $headers = implode("\n", $headers); var_dump($headers); exit;
$_POST['something'] = array_map(intval,$_POST['something']);
array_walk($ids, create_function('&$val', '$val = trim($val);'));
这篇关于array_walk()使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!