PHP:array_map遍历元素并调用函数

Lasted 2020-01-25 14:35:12

array_map() 函数对数组的每个元素应用回调函数。

定义

array_map ( callable $callback , array $array1 [, array $... ] ) : array

返回数组,为 $array1 每个元素调用 callback 方法,并返回新数组。函数参数的数量跟数组的数量必须一样。

示例 

计算元素乘积 

<?php
function callback($v)
{
  return($v*$v);
}

$a = array(1, 2, 3, 4, 5);
print_r(array_map("callback", $a));
Array
(
  [0] => 1
  [1] => 4
  [2] => 9
  [3] => 16
  [4] => 25
)

比较两个数组的元素是否相等

<?php
function fun($v1, $v2)
{
  if ($v1===$v2)
  {
    return "same";
  }
  return "different";
}

$a1=array("Horse", "Dog", "Cat");
$a2=array("Cow", "Dog", "Rat");
print_r(array_map("fun", $a1, $a2));
Array
(
  [0] => different
  [1] => same
  [2] => different
)

回调函数为空 NULL

<?php
$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
  )
)