数组函数 array_map
时间:2006-05-24 来源:jingzhi
array array_map ( callback callback, array arr1 [, array ...] )
array_map() 返回一个数组,该数组包含了 arr1 中的所有单元经过 callback 作用过之后的单元。callback 接受的参数数目应该和传递给 array_map() 函数的数组数目一致。
通常使用了两个或更多数组时,它们的长度应该相同,因为回调函数是平行作用于相应的单元上的。如果数组的长度不同,则最短的一个将被用空的单元扩充。
本函数一个有趣的用法是构造一个数组的数组,这可以很容易的通过用 NULL 作为回调函数名来实现。
例子 3. 建立一个数组的数组
= 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);
?>
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:
= 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
)
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
)
)
相关阅读 更多 +