(PHP 4 >= 4.0.6, PHP 5)
array_map -- 將回調函式作用到給定數組的單元上
說明
array array_map ( callback callback, array arr1 [, array ...] )
array_map() 返回一個數組,該數組包含了 arr1 中的所有單元經過 callback 作用過之後的單元。callback 接受的參數數目應該和傳遞給 array_map() 函式的數組數目一致。
例 1. array_map() 例子
function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>
這使得 $b 成為:
Array
(
[0] => 1
[1] => 8
[2] => 27
[3] => 64
[4] => 125
)
例 2. array_map() - 使用更多的數組
function 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
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
)
)
通常使用了兩個或更多數組時,它們的長度應該相同,因為回調函式是平行作用於相應的單元上的。如果數組的長度不同,則最短的一個將被用空的單元擴充。
本函式一個有趣的用法是構造一個數組的數組,這可以很容易的通過用 NULL 作為回調函式名來實現。
例 3. 建立一個數組的數組
$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
)
)
bturchik at iponweb dot net
19-Jul-2007 02:46
Maybe this one will be useful for someone:
function array_map_helper($mapper, $array) {
$mapper = preg_replace('/^return (.*?);$/', '$1', trim($mapper));
$result = array();
if (preg_match('/(\(?)(.*?)\s*=>\s*(.*?)(\)?)$/', $mapper, $matches)) {
list($full_found, $array_open, $left, $right, $array_close) = $matches;
if ($array_open && $array_close) {
$mapper = '$result[] = array' . $full_found . ';';
} else {
$mapper = '$result[' . $left . '] = ' . $right . ';';
}
} else {
$mapper = '$result[] = ' . $mapper . ';';
}
foreach ($array as $key => $value) {
eval($mapper);
}
return $result;
}
should be used like:
$array = array(array('foo' => 11, 'bar' => 22),
array('foo' => 111, 'bar' => 222),
array('foo' => 1111, 'bar' => 2222));
$mapped = array_map_helper('$value["foo"] => $value["bar"]', $array);
var_dump will give
array(3) {
[11]=>
int(22)
[111]=>
int(222)
[1111]=>
int(2222)
}
or
$mapped = array_map_helper('$value["foo"]', $array);
var_dump will give
array(3) {
[0]=>
int(11)
[1]=>
int(111)
[2]=>
int(1111)
}
or
$mapped = array_map_helper('$value["foo"] + $value["bar"] . " at position $key"', $array);
var_dump will give
array(3) {
[0]=>
string(16) "33 at position 0"
[1]=>
string(17) "333 at position 1"
[2]=>
string(18) "3333 at position 2"
}
andref dot dias at pronus dot eng dot br
24-Oct-2006 07:14
A recursive way to handle multidimensional arrays:
function multidimensionalArrayMap( $func, $arr )
{
$newArr = array();
foreach( $arr as $key => $value )
{
$newArr[ $key ] = ( is_array( $value ) ? multidimensionalArrayMap( $func, $value ) : $func( $value ) );
}
return $newArr;
}
?>
pcdinh at phpvietnam dot net
18-Mar-2006 04:50
Hi benjaminhill,
You can apply a method of a instantiated class to array_maps as follows:
class Maths {
function addOne($input) {
return ($input + 1);
}
}
$maths = new Maths();
$sum = array_map(array($maths, \\\'addOne\\\'), array(1, 2));
// where $maths is the object which has been instantiated before and addOne is its method without its own parameters
var_dump($sum);
The code fragment will return:
array
0 => 2
1 => 3
However, I love a syntax like this:
$sum = array_map($maths->addOne($this), array(1, 2));
where $this should be interpreted as each values extracted from the subsequent array, which in this case is array(1, 2).
This syntax reminds me of Javascript syntax.
PHP\\\'s callback mechanism should be improved.
26-Aug-2005 01:57
Here's a function, very helpfull to me, that allows you to map your callback on mixed args.
function array_smart_map($callback) {
// Initialization
$args = func_get_args() ;
array_shift($args) ; // suppressing the callback
$result = array() ;
// Validating parameters
foreach($args as $key => $arg)
if(is_array($arg)) {
// the first array found gives the size of mapping and the keys that will be used for the resulting array
if(!isset($size)) {
$keys = array_keys($arg) ;
$size = count($arg) ;
// the others arrays must have the same dimension
} elseif(count($arg) != $size) {
return FALSE ;
}
// all keys are suppressed
$args[$key] = array_values($arg) ;
}
// doing the callback thing
if(!isset($size))
// if no arrays were found, returns the result of the callback in an array
$result[] = call_user_func_array($callback, $args) ;
else
for($i=0; $i<$size; $i++) {
$column = array() ;
foreach($args as $arg)
$column[] = ( is_array($arg) ? $arg[$i] : $arg ) ;
$result[$keys[$i]] = call_user_func_array($callback, $column) ;
}
return $result ;
}
?>
Trying with :
// $_GET is ?foo=bar1-bar2-bar3&bar=foo1
print_r(array_smart_map('explode', '-', $_GET)) ;
?>
Returns :
array(
[foo] => array(
0 => bar1
1 => bar2
2 => bar3
)
[bar] => array(
1 => foo1
)
)
david dot tulloh at infaze dot com dot au
06-Jul-2005 11:53
You can pass values to array_map by reference, essentially allowing you to use it as you would array_walk with multiple arrays as parameters.
A trivial example:
$a = array(1,2,3,4,5);
$add_func = create_function('&$x, $y', '$x+=$y;');
array_map($add_func, $a, $a);
print_r($a);
?>
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)
Vinicius Cubas Brand
23-Mar-2005 01:31
The following function does exaclty the same thing of array_map. However, maintains the same index of the input arrays
function array_map_keys($param1,$param2,$param3=NULL)
{
$res = array();
if ($param3 !== NULL)
{
foreach(array(2,3) as $p_name)
{
if (!is_array(${'param'.$p_name}))
{
trigger_error(__FUNCTION__.'(): Argument #'.$p_name.' should be an array',E_USER_WARNING);
return;
}
}
foreach($param2 as $key => $val)
{
$res[$key] = call_user_func($param1,$param2[$key],$param3[$key]);
}
}
else
{
if (!is_array($param2))
{
trigger_error(__FUNCTION__.'(): Argument #2 should be an array',E_USER_WARNING);
return;
}
foreach($param2 as $key => $val)
{
$res[$key] = call_user_func($param1,$param2[$key]);
}
}
return $res;
}
?>
For instance:
$arr1 = array(
'3' => 'a',
'4' => 'b',
'5' => 'c'
);
$arr2 = array(
'3' => 'd',
'4' => 'e',
'5' => 'f'
);
$arr3 = array_map_keys(create_function('$a,$b','return $a.$b;'),$arr1,$arr2);
print_r($arr3);
?>
The result will be:
Array
(
[3] => ad
[4] => be
[5] => cf
)
endofyourself at yahoo dot com
20-Feb-2005 07:29
If you need to call a static method from array_map, this will NOT work:
array_map('myclass::myMethod' , $value);
?>
Instead, you need to do this:
array_map( array('myclass','myMethod') , $value);
?>
It is helpful to remember that this will work with any PHP function which expects a callback argument.
nd0 at gmx dot de
02-Jul-2004 11:42
array_map works also fine with create_function:
$a = array(1, 2, 3, 4, 5);
$b = array_map(create_function('$n', 'return $n*$n*$n;'), $a);
print_r($b);
?>
if you want to manipulate the elements of the array, instead to on a copy,
than take a look at array_walk:
$a = array(1, 2, 3, 4, 5);
array_walk($a, create_function('&$n', '$n = $n*$n*$n;'));
print_r($a);
?>
The Result of both is:
Array
(
[0] => 1
[1] => 8
[2] => 27
[3] => 64
[4] => 125
)
bishop
10-Apr-2004 12:07
Occasionally, you may find that you need to pull out a column (or several) from an array. Here's a map-like function to do that:
function &array_shear(&$arrays, $idx1 /* ... */) {
$indexes = func_get_args();
array_shift($indexes);
$newArrays = array ();
foreach (array_keys($arrays) as $arrayKey) {
$newArray = array ();
foreach ($indexes as $index) {
$newArray[$index] = $arrays[$arrayKey][$index];
unset($arrays[$arrayKey][$index]);
}
$newArrays[$arrayKey] = $newArray;
}
return $newArrays;
}
?>
So, doing this:
$t1 = array (
2 => array ('a', 'b', 'c'),
1 => array ('d', 'e', 'f'),
5 => array ('g', 'h', 'i'),
);
$t2 = array_shear($t1, 1, 0);
?>
will result in:
$t1 = array (
2 => array ( 2 => 'c', ),
1 => array ( 2 => 'f', ),
5 => array ( 2 => 'i', ),
);
$t2 = array (
2 => array ( 1 => 'b', 0 => 'a', ),
1 => array ( 1 => 'e', 0 => 'd', ),
5 => array ( 1 => 'h', 0 => 'g', ),
);
?>
stephen at mu dot com dot au
07-Jan-2003 06:02
A note when doing something allong the lines of:
class foo {
var $var;
function bar() {
array_map(array($this, "baz"), array(1,2,3));
}
function baz($arg) {
$this->var = $this->var + $arg;
}
}
?>
This will *not* work as expected. You need to pass $this by reference as with:
array_map(array(&$this, "baz"), array(1,2,3));
or you'll be making a copy of the object each time, changing a value, then throwing the result away.
dan at mojavelinux dot com
15-Jun-2002 05:07
Here is a better, more true version of a deep array_map. The only negative of this function is that the array is passed by reference, so just be aware of that. (patches welcome)
function array_map_deep(&$in_array, $in_func, $in_args = array(), $in_index = 1) {
// fix people from messing up the index of the value
if ($in_index < 1) {
$in_index = 1;
}
foreach (array_keys($in_array) as $key) {
// we need a reference, not a copy, normal foreach won't do
$value =& $in_array[$key];
// we need to copy args because we are doing
// manipulation on it farther down
$args = $in_args;
if (is_array($value)) {
array_map_deep($value, $in_func, $in_args, $in_index);
}
else {
array_splice($args, $in_index - 1, $in_index - 1, $value);
$value = call_user_func_array($in_func, $args);
}
}
return $in_array;
}
?>
This is a neat function because you can pass an array, a function, and an array of parameters, and finally, and index of where in the array of parameters for the callback function the contents you are mapping should get replaced. This index is human based (starts at 1), and can be used in something like a preg_replace callback, where the contents must be the 3rd index. Enjoy!
相關詞條
-
array_map
定義用法array_map() 函式返回用戶自定義函式作用後的數組。回調函式接受的參數數目應該和傳遞給 array_map() 函式的數組數目一致。語法array_map(function,array1...
-
php數組
鍵名。 array_map() 將用戶自定義函式作用到給定數組的每個值上...
基本語法 : PHP 數組 PHP 5 Array 函式 語法 實用函式 -
PHP5範例代碼查詢辭典
array_map()向數組元素套用函式 1474-35 使用...
摘要 目錄 -
Array函式
() 返回數組中所有的鍵名。 array_map() 將用戶自定義函式作...
功能 語法 說明 示例 其他 -
PHPArray函式
。 4 array_map() 將回調函式作用到給定數組的單元上。 4...
-
Array
() 返回數組中所有的鍵名。 array_map() 將用戶自定義函式作...
PHP 5 Array 函式 VBS array 函式 方法摘要 對象 詳細信息 -
addslashes
) ? array_map('stripslashes_deep...
函式定義 參數說明 使用場景 使用示例 實例 -
數組函式館
array_map — 將回調函式作用到給定數組的單元上...
簡介 需求 安裝 運行時配置 資源類型 -
array[數組]
() 返回數組中所有的鍵名。 array_map() 將用戶自定義函式作...
PHP 5 Array 函式 VBS array 函式 方法摘要 對象 詳細信息