php数组函数-array_map()
array_map()函数返回用户自定义函数作用后的数组。回调函数接受的参数
数目应该和传递给array_map()函数的数组数目一直。
array_map(function,array1,array2,array3...);
function:必需。用户自定义的函数名称,或者是null
array1:必需。规定数组
array2:可选。规定数组
array3:可选。规定数组
function myfunction($v){
if($v === 'Dog'){
return 'Fido';
}
return $v;
}
$a = array('Horse','Dog','Cat');
print_r(array_map('myfunction',$a));
?>
输出:Array ( [0] => Horse [1] => Fido [2] => Cat )
使用多个参数:
function myfunction($v1,$v2){
if($v1 === $v2){
return "same";
}else{
return "different";
}
}
$a1 = array("Horse","Dog","Cat");
$a2 = array("Cow","Dog","Rat");
print_r(array_map('myfunction',$a1,$a2));
?>
输出:Array ( [0] => different [1] => same [2] => different )
自定义函数名设置为null时:
$a1 = array("Dog","Cat");
$a2 = array("Puppy","Kitten");
print_r(array_map(null,$a1,$a2));
?>
输出:Array ( [0] => Array ( [0] => Dog [1] => Puppy ) [1] =>
Array ( [0] => Cat [1] => Kitten ) )