array_walk() - 使用用户自定义函数对数组中的每个元素做回调处理 - php 数组函数
array_walk()
(PHP 4, PHP 5, PHP 7)
使用用户自定义函数对数组中的每个元素做回调处理
说明
array_walk(array &$array,callable$callback[,mixed $userdata=NULL]): bool将用户自定义函数$funcname应用到$array数组中的每个单元。
array_walk()不会受到$array内部数组指针的影响。array_walk()会遍历整个数组而不管指针的位置。
参数
$array输入的数组。
$callback典型情况下$callback接受两个参数。$array参数的值作为第一个,键名作为第二个。
Note:如果$callback需要直接作用于数组中的值,则给$callback的第一个参数指定为引用。这样任何对这些单元的改变也将会改变原始数组本身。Note:
参数数量超过预期,传入内置函数(例如strtolower()),将抛出警告,所以不适合当做$funcname。
只有$array的值才可以被改变,用户不应在回调函数中改变该数组本身的结构。例如增加/删除单元,unset 单元等等。如果array_walk()作用的数组改变了,则此函数的的行为未经定义,且不可预期。
$userdata如果提供了可选参数$userdata,将被作为第三个参数传递给callback$funcname。
返回值
成功时返回TRUE
,或者在失败时返回FALSE
。
错误/异常
如果$callback函数需要的参数比给出的多,则每次array_walk()调用$callback时都会产生一个E_WARNING级的错误。
范例
Example #1array_walk()例子
以上例程会输出:
Before ...: d. lemon a. orange b. banana c. apple ... and after: d. fruit: lemon a. fruit: orange b. fruit: banana c. fruit: apple
参见
array_walk_recursive()
对数组中的每个成员递归地应用用户函数iterator_apply()
为迭代器中每个元素调用一个用户自定义函数list()
把数组中的值赋给一组变量each()
返回数组中当前的键/值对并将数组指针向前移动一步call_user_func_array()
调用回调函数,并把一个数组参数作为回调函数的参数array_map()
为数组的每个元素应用回调函数- callback类型的信息
- foreach
It's worth nothing that array_walk can not be used to change keys in the array. The function may be defined as (&$value, $key) but not (&$value, &$key). Even though PHP does not complain/warn, it does not modify the key.
I noticed that : PHP ignored arguments type when using array_walk() even if there was declare(strict_types=1) . See this code as an example ... The output is : butter: 5 meat: 7 banana: 3 whilst the expecting output is : Fatal error: Uncaught TypeError: Argument 1 passed to test_print() must be of the type integer because "butter" => 5.3 is float I asked someone about it and they said "this was caused by the fact that callbacks called from internal code will always use weak type". But I tried to do some tests and this behavior is not an issue when using call_user_func().
Calling an array Walk inside a class 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'));
If you want to unset elements from the callback function, maybe what you really need is array_filter.
Since array_walk cannot modify / change / reindex keys as already mentioned, i provide this small wrapping function which accomplishes passing array reference and index using closures , "use" keyword. function indexArrayByElement($array, $element) { $arrayReindexed = []; array_walk( $array, function ($item, $key) use (&$arrayReindexed, $element) { $arrayReindexed[$item[$element]] = $item; } ); return $arrayReindexed; }
// We can make that with this simple FOREACH loop : $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); foreach($fruits as $cls => $vls) { $fruits[$cls] = "fruit: ".$vls; } Results: Array ( [d] => fruit: lemon [a] => fruit: orange [b] => fruit: banana [c] => fruit: apple )
It can be very useful to pass the third (optional) parameter by reference while modifying it permanently in callback function. This will cause passing modified parameter to next iteration of array_walk(). The exaple below enumerates items in the array: This outputs: Array ( [0] => 1 lemon [1] => 2 orange [2] => 3 banana [3] => 4 apple ) $num is: 1 Notice at the last line of output that outside of array_walk() the $num parameter has initial value of 1. This is because array_walk() does not take the third parameter by reference.. so what if we pass the reference as the optional parameter..
There is a note about 3 years ago regarding using this for trimming. array_map() may be cleaner for this. I haven't checked the time/resource impact: $result = array_map("trim", $array);
Don't forget about the array_map() function, it may be easier to use! Here's how to lower-case all elements in an array:
Unfortunately I spent a lot of time trying to permanently apply the effects of a function to an array using the array_walk function when instead array_map was what I wanted. Here is a very simple though effective example for those who may be getting overly frustrated with this function...
array_walk does not work on SplFixedArray objects: result is: test_1 test_2
You can use lambda function as a second parameter: Example (multiply positive values by two):
Using lambdas you can create a handy zip function to zip together the keys and values of an array. I extended it to allow you to pass in the "glue" string as the optional userdata parameter. The following example is used to zip an array of email headers:
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!