array_map — 返回一個運行過回調函數的數據。
說明
array array_map ( callback callback, array arr1 [, array ...] )
array_map() 返回一個數組,該數組包含了 arr1 中的所有單元經過 callback 作用過之后的單元。callback 接受的參數數目應該和傳遞給 array_map() 函數的數組數目一致。
例 1. array_map() 例子
<?phpfunction cube($n){return($n * $n * $n);}$a = array(1, 2, 3, 4, 5);$b = array_map("cube", $a);print_r($b);?>
Array([0] => 1[1] => 8[2] => 27[3] => 64[4] => 125)
<?phpfunction show_Spanish($n, $m){return("The number $n is called $m in Spanish");}function map_Spanish($n, $m){return(array($n => $m));}$a = array(1, 2, 3, 4, 5);$b = array("uno", "dos", "tres", "cuatro", "cinco");$c = array_map("show_Spanish", $a, $b);print_r($c);$d = array_map("map_Spanish", $a , $b);print_r($d);?>
// printout of $c www.it165.netArray([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[3] => The number 4 is called cuatro in Spanish[4] => The number 5 is called cinco in Spanish)// printout of $dArray([0] => Array([1] => uno)[1] => Array([2] => dos)[2] => Array([3] => tres)[3] => Array([4] => cuatro)[4] => Array([5] => cinco))
通常使用了兩個或更多數組時,它們的長度應該相同,因為回調函數是平行作用于相應的單元上的。如果數組的長度不同,則最短的一個將被用空的單元擴充。
本函數一個有趣的用法是構造一個數組的數組,這可以很容易的通過用 NULL 作為回調函數名來實現。
例 3. 建立一個數組的數組
<?php$a = array(1, 2, 3, 4, 5);$b = array("one", "two", "three", "four", "five");$c = array("uno", "dos", "tres", "cuatro", "cinco");$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)[3] => Array([0] => 4[1] => four[2] => cuatro)[4] => Array([0] => 5[1] => five[2] => cinco))
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答