PHP array_map() 函数详解
定义
array_map - 对给定的诸多数组使用回调函数
描述
array_map ( callable $callback , array $array1 [, array $... ] ) : array
将传入的数组按对应值传递给回调函数,回调函数处理结果组成新的数组作为返回值返回;
传入的数组个数必须与回调函数的形参个数相同。
示例一
<?php
function show_Spanish($n, $m)
{
return "The number {$n} is called {$m} in Spanish";
}
$a = [1, 2, 3];
$b = ['uno', 'dos', 'tres'];
$c = array_map('show_Spanish', $a, $b);
print_r($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
)
示例二
如果传入多个数组,每个数组的长度必须相同,否组,短的数组会用空值扩充成对应长度。
这个函数可用于构建一个多维数组( zip operation of arrays ),像下面这样
<?php
$a = [1, 2, 3];
$b = ['one', 'two', 'three'];
$c = ['uno', 'dos', 'tres'];
$d = array_map(null, $a, $b, $c);
print_r($d);
?>
将输出:
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
)
)
作者:皎然CEO
链接:https://www.cnblogs.com/jiaoran/p/12636327.html
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦(っ•̀ω•́)っ✎⁾⁾!