Home  >  Article  >  Backend Development  >  PHP数组函数array_map()使用详解

PHP数组函数array_map()使用详解

WBOY
WBOYOriginal
2016-06-20 13:04:161337browse

定义和用法array_map() 函数返回用户自定义函数作用后的数组。

回调函数接受的参数数目应该和传递给 array_map() 函数的数组数目一致。

语法array_map(function,array1,array2,array3...) 参数描述function必需。

用户自定义函数的名称,或者是 null。array1必需。规定数组。array2可选。规定数组。array3可选。规定数组。

例子 1 

<span style="font-size: 14px;"><?php</span><br />function myfunction($v) {<br />if ($v === "Dog") {<br />return "Fido";<br />}<br />return $v;<br />}<br /><br />$a = array("Horse", "Dog", "Cat");<br />print_r(array_map("myfunction", $a));<br /><p>?><span style="font-size: 14px;">

输出:

Array ( [0] => Horse [1] => Fido [2] => Cat )

例子 2 

使用多个参数:

<span style="font-size: 14px;"><?php</span><br />function myfunction($v1, $v2) {<br />if ($v1 === $v2) {<br />return "same";<br />}<br />return "different";<br />}<br /><br />$a1 = array("Horse", "Dog", "Cat");<br />$a2 = array("Cow", "Dog", "Rat");<br />print_r(array_map("myfunction", $a1, $a2));<br /><p>?><span style="font-size: 14px;">

输出:

Array ( [0] => different [1] => same [2] => different )

例子 3 

请看当自定义函数名设置为 null 时的情况:

<span style="font-size: 14px;"><?php</span><br />$a1 = array("Dog", "Cat");<br />$a2 = array("Puppy", "Kitten");<br />print_r(array_map(null, $a1, $a2));<br /><p>?><span style="font-size: 14px;">

输出:

Array (

[0] => Array ( [0] => Dog [1] => Puppy )
[1] => Array ( [0] => Cat [1] => Kitten )
)


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn