当前位置: 首页 > 网络学院 > 服务端脚本教程 > PHP > array_map() 函数
The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function.
array_map()函数将一个数组中的每个值都发送到用户自定义函数中,并返回这个自定义函数中的数组值。
array_map(function,array1,array2,array3...) |
| Parameter 参数 | Description 描述 |
|---|---|
| function | Required. The name of the user-made function, or null 必要函数。指定自定义函数的名称,或者不设定(空值) |
| array1 | Required. Specifies an array 必要函数。指定一个数组 |
| array2 | Optional. Specifies an array 可选函数。指定一个数组 |
| array3 | Optional. Specifies an array 可选函数。指定一个数组 |
Tip: You can assign one array to the function, or as many as you like.
提示:你可以给函数制定一个数组,数组的数量不限。
<?php
function myfunction($v)
{
if ($v==="Dog") { return "Fido"; }
return $v;
}
$a=array("Horse","Dog","Cat");
print_r(array_map("myfunction",$a));
?> |
The output of the code above will be:
上述代码将输出下面的结果:
Array ( [0] => Horse [1] => Fido [2] => Cat ) |
Using the more than one parameter.
使用多个参数:
<?php
function myfunction($v1,$v2)
{
if ($v1===$v2) { return "same"; }
return "different";
}
$a1=array("Horse","Dog","Cat");
$a2=array("Cow","Dog","Rat");
print_r(array_map("myfunction",$a1,$a2));
?> |
The output of the code above will be:
上述代码将输出下面的结果:
Array ( [0] => different [1] => same [2] => different ) |
Look what happens if you assign null as the functionname:
如果你给函数名称指定空值,看看会发生什么:
<?php
$a1=array("Dog","Cat");
$a2=array("Puppy","Kitten");
print_r(array_map(null,$a1,$a2));
?> |
The output of the code above will be:
上述代码将输出下面的结果:
Array ( [0] => Array ( [0] => Dog [1] => Puppy ) [1] => Array ( [0] => Cat [1] => Kitten ) ) |
评论 (0) All