定义

array_map – 对给定的诸多数组使用回调函数

描述

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

将传入的数组按对应值传递给回调函数,回调函数处理结果组成新的数组作为返回值返回;
传入的数组个数必须与回调函数的形参个数相同。

示例一

<?php
function show_spanish($n, $m)
{
    return "the number {$n} is called {$m} in spanish";
}

$a = [1, 2, 3];
$b = ['uno', 'dos', 'tres'];

$c = array_map('show_spanish', $a, $b);
print_r($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
)

示例二

如果传入多个数组,每个数组的长度必须相同,否组,短的数组会用空值扩充成对应长度。
这个函数可用于构建一个多维数组( zip operation of arrays ),像下面这样

<?php
$a = [1, 2, 3];
$b = ['one', 'two', 'three'];
$c = ['uno', 'dos', 'tres'];

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