array_map() - 为数组的每个元素应用回调函数 - php 数组函数
array_map()
(PHP 4 >= 4.0.6, PHP 5, PHP 7)
为数组的每个元素应用回调函数
说明
array_map(callable$callback,array $array1[,array $...]): arrayarray_map():返回数组,是为$array1每个元素应用$callback函数之后的数组。$callback函数形参的数量和传给array_map()数组数量,两者必须一样。
参数
$callback回调函数,应用到每个数组里的每个元素。
$array1数组,遍历运行$callback函数。
数组列表,每个都遍历运行$callback函数。
返回值
返回数组,包含$callback函数处理之后$array1的所有元素。
范例
Example #1array_map()例子
这使得$b成为:
Array ( [0] => 1 [1] => 8 [2] => 27 [3] => 64 [4] => 125 )
Example #2array_map()使用匿名函数(PHP 5.3.0 起)
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )
Example #3array_map():使用更多的数组
以上例程会输出:
// printout of $c Array ( [0] => The number 1 is called uno in Spanish [1] => The number 2 is called dos in Spanish [2] => The number 3 is called tres in Spanish [3] => The number 4 is called cuatro in Spanish [4] => The number 5 is called cinco in Spanish ) // printout of $d Array ( [0] => Array ( [1] => uno ) [1] => Array ( [2] => dos ) [2] => Array ( [3] => tres ) [3] => Array ( [4] => cuatro ) [4] => Array ( [5] => cinco ) )
传入两个及以上的数组时,它们元素数量将会相同。因为回调函数会并行地处理相互对应的元素。如果几个数组的元素数量不一致:空元素会扩展短那个数组,直到长度和最长的数组一样。
此函数有个有趣的用法:传入NULL
作为回调函数的名称,将创建多维数组(一个数组,内部包含数组。)
多维数组:创建数组,内部包含数组
以上例程会输出:
Array ( [0] => Array ( [0] => 1 [1] => one [2] => uno ) [1] => Array ( [0] => 2 [1] => two [2] => dos ) [2] => Array ( [0] => 3 [1] => three [2] => tres ) [3] => Array ( [0] => 4 [1] => four [2] => cuatro ) [4] => Array ( [0] => 5 [1] => five [2] => cinco ) )
如果仅传入一个数组,键(key)会保留;传入多个数组,键(key)是整型数字的序列。
Example #5array_map()键(key)是 string
以上例程会输出:
array(1) { ["stringkey"]=> array(1) { [0]=> string(5) "value" } } array(1) { [0]=> array(2) { [0]=> string(5) "value" [1]=> string(5) "value" } } array(1) { ["stringkey"]=> string(5) "value" } array(1) { [0]=> array(2) { [0]=> string(5) "value" [1]=> string(5) "value" } }
参见
array_filter()
用回调函数过滤数组中的单元array_reduce()
用回调函数迭代地将数组简化为单一的值array_walk()
使用用户自定义函数对数组中的每个元素做回调处理- callback类型的信息
I was miffed that array_map didn't have a way to pass values *and* keys to the callback, but then I realized I could do this: function callback($k, $v) { ... } array_map( "callback", array_keys($array), $array);
If you need to call a static method from array_map, this will NOT work: Instead, you need to do this: It is helpful to remember that this will work with any PHP function which expects a callback argument.
PHP 5.3 enables us to use inline anonymous functions with array_map, cleaning up the syntax slightly. This was possible (although not recommended) in prior versions of PHP 5, via create_function().
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!