PHP 的 array_map 對於處理資料來說很好用,可以把原始資料透過簡單的轉換變成符合想要使用的格式,語法如下:
array_map(callable|null $callback, array $array, array ...$arrays): array
範例一:
function cube($n) { return ($n * $n * $n); } $a = [1, 2, 3, 4, 5]; $b = array_map('cube', $a); print_r($b);
這樣可以得到輸入的內容三階層的新的值的陣列。
範例二:
$func = function($value) { return $value * 2; }; print_r(array_map($func, range(1, 5)));
可以得到一個 [2,4,6,8,10] 的陣列。
範例三:
$products=[ [ "product_id"=>1 ], [ "product_id"=>2 ], [ "product_id"=>3 ] ]; $arr=array_map(function($value){ return $value["product_id"]; }, $products); print_r($arr);
這樣就可以把值給過濾出來變成一個單純的陣列。
範例四:使用多個陣列
function show_Spanish($n, $m) { return "The number {$n} is called {$m} in Spanish"; } function map_Spanish($n, $m) { return [$n => $m]; } $a = [1, 2, 3, 4, 5]; $b = ['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 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 [3] => The number 4 is called cuatro in Spanish [4] => The number 5 is called cinco in Spanish ) // printout of $d Array ( [0] => Array ( [1] => uno ) [1] => Array ( [2] => dos ) [2] => Array ( [3] => tres ) [3] => Array ( [4] => cuatro ) [4] => Array ( [5] => cinco ) )