PHP array_map() 函數詳解

定義

array_map - 對給定的諸多數組使用回調函數php


描述

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 ),像下面這樣code

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

$d = array_map(null, $a, $b, $c);
print_r($d);
?>

將輸出:three

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
        )
)
相關文章
相關標籤/搜索