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