标签:名称 function func 定义函数 ret 一个 led val 输入
PHP array_map 一个有趣的函数
定义和用法
array_map() 函数将用户自定义函数作用到数组中的每个值上,并返回用户自定义函数作用后的带有新值的数组。
回调函数接受的参数数目应该和传递给 array_map() 函数的数组数目一致。
提示:您可以向函数输入一个或者多个数组。
语法
array_map(myfunction, array1, array2, array3 ...)
参数 描述
myfunction 必需。用户自定义函数的名称,或者是 null。
array1 必需。规定数组。
array2 可选。规定数组。
array3 可选。规定数组。
技术细节
返回值: 返回包含 array1 的值的数组,在向每个值应用自定义函数后。
返回一个数组,该数组的每个元素都数组(array1)里面的每个元素经过回调函数(myfunction)处理了的。
用例1
<?php
function myfunction($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("myfunction", $a);
print_r($b);
?>
返回结果
Array
(
[0] => 1
[1] => 8
[2] => 27
[3] => 64
[4] => 125
)
用例2
<?php
$myfunction= function($value) {
return $value * 2;
};
print_r(array_map($myfunction, range(1, 5)));
?>
返回结果
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)
用例3 使用更多的数组
<?php
function show_Spanish($n, $m)
{
return("The number $n is called $m in Spanish");
}
function map_Spanish($n, $m)
{
return(array($n => $m));
}
$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");
$c = array_map("show_Spanish", $a, $b);
print_r($c);
$d = array_map("map_Spanish", $a , $b);
print_r($d);
?>
返回结果
// 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
)
)
用例4 建立一个数组的数组
<?php
$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");
$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
)
[3] => Array
(
[0] => 4
[1] => four
[2] => cuatro
)
[4] => Array
(
[0] => 5
[1] => five
[2] => cinco
)
)
标签:名称 function func 定义函数 ret 一个 led val 输入
原文地址:https://www.cnblogs.com/haoyuekey/p/12794053.html