php array pluck,PHP 将回调函数作用到给定数组的单元上

用户评论:

hrvoj3e at gmail dot com (2013-04-30 14:38:42)

Why not use

mb_convert_case($str, MB_CASE_TITLE, "UTF-8");

Works for me! :)

pfbouquet at gmail dot com (2013-04-07 12:30:26)

Easy way to convert array into Utf_8 :

{

if(is_array($array))

{

returnarray_map("utf8_encode_clever",$array);

}

else

{

returnutf8_encode($array);

}

}// here, we will call our function to convert $data :$data=utf8_encode_clever($data);?>

James (2013-03-15 17:07:05)

array_map() can be applied to assoc arrays without affecting the keys

shakespeare32 at gmail dot com (2013-02-19 19:01:38)

Why not an array of callbacks?

if (!$callbacks) { return$array; }

if (!is_array($callbacks) &&is_string($callbacks) &&function_exists($callbacks)) {

returnarray_map($callbacks,$array);

}

foreach($callbacksas$callback) {

if (function_exists($callback)) {$array=array_map($callback,$array);

}

}

return$array;

}?>

godek dot maciek at gmail dot com (2012-04-19 07:01:43)

I came up with a convenient syntax for method application, particularly useful inside the array_map.

For instance, if you want to

array_map(function($object, $arg1) { return $object->method($arg1, "arg2"); }, $objects, $args1);

it is possible to provide a shorthand:

global $_; // necessary inside a function, unfortunately

array_map($_->method($_, "arg2"), $objects, $args1);

Here's the implementation (works with 5.3)

function m_caller($method) {

$args = func_get_args();

array_shift($args);

return function($object) use($method, $args) {

global $_;

$local_args = func_get_args();

array_shift($args);

if(!is_object($object)) {

// error

}

$reflection = new ReflectionMethod(get_class($object), $method);

foreach($args as $key => $arg) {

if($arg === $_) {

$args[$key] = array_shift($local_args);

}

}

return $reflection->invokeArgs($object, array_merge($args, $local_args));

};

}

class MethodCaller {

public function __call($name, $arguments) { return call_user_func_array('m_caller', array_merge(array($name), $arguments)); }

public function __get($name) { return m_caller($name); }

};

$_ = new MethodCaller();

qeremy (2012-03-07 10:35:00)

An alternative for recursive mapping;

foreach ($arras$k=>$v) {$rarr[$k] =is_array($v)

?array_map_recursive($fn,$v)

:$fn($v);// or call_user_func($fn, $v)}

return$rarr;

}

functionsqr($x) {

return"$x^ 2 = ". ($x*$x);

}$a= array(1,2,3, array(4, array(5)));$b=array_map_recursive("sqr",$a);print_r($b);?>

Array

(

[0] => 1 ^ 2 = 1

[1] => 2 ^ 2 = 4

[2] => 3 ^ 2 = 9

[3] => Array

(

[0] => 4 ^ 2 = 16

[1] => Array

(

[0] => 5 ^ 2 = 25

)

)

)

gmail.com@mspreij (2012-02-26 22:48:19)

Hope I'm not late to the party, here's my function to apply array_map to the *keys* of an array.

Extra array arguments will be used for the callback function's parameters just like with array_map, with the difference that a string is also allowed: it will just be used to create an array of appropriate length with as each value that string. Arrays are left alone (and will be padded with nulls by array_map as needed).

// array_map_keys($callback, $array, [$args, ..]) /functionarray_map_keys($callback,$array/* [, $args ..] */) {$args=func_get_args();

if (!is_callable($callback))trigger_error("first argument (callback) is not a valid function",E_USER_ERROR);

if (!is_array($array))trigger_error("second argument must be an array",E_USER_ERROR);$args[1] =array_keys($array);// If any additional arguments are not arrays, assume that value is wanted for every $array item.

// array_map() will pad shorter arrays with Null valuesfor ($i=2;$i

if (!is_array($args[$i])) {$args[$i] =array_fill(0,count($array),$args[$i]);

}

}

returnarray_combine(call_user_func_array('array_map',$args),$array);

}// Some examples:$arr= array('foo'=>123,'bar'=>456);// simply uppercase keys:var_dump(array_map_keys('strtoupper',$arr));// or..var_dump(array_map_keys(function($input) {returnstrtoupper($input);},$arr));// >> array(2) { ["FOO"]=>int(123) , ["BAR"]=> int(456) }

// Add a prefix 'myvar_':var_dump(array_map_keys(function($input,$prefix) {return$prefix.$input;},$arr,'myvar_'));// >> array(2) { ["myvar_foo"]=>int(123) , ["myvar_bar"]=>int(456) }

// Apart from the (static string) prefix, we also number them:$arr= array('foo'=>123,'bar'=>456,'bazz'=>789,'yadda'=>'0AB');var_dump(array_map_keys(function($input,$middle,$number) {return$number.':'.$middle.$input;},$arr,'myvar_',range(1,count($arr))));// >> array(4) { ["1:myvar_foo"]=>int(123) , ["2:myvar_bar"]=>int(456) , ["3:myvar_bazz"]=>int(789) , ["4:myvar_yadda"]=>string(3) "0AB" }?>

php/hotblocks/nl (2011-11-28 05:00:17)

Note that the $arr argument has to be an array, not just a Traversable/Iterator.

For instance this won't work:

$documents=$mongo->db->collection->find();// $documents is Traversable by foreach$ids=array_map(function($document) {

return$document['_id'];

},$objects);// $ids will now be NULL, because $documents wasn't an Array?>

A solution is to first use iterator_to_array():

$ids=array_map(function($document) {

return$document['_id'];

},iterator_to_array($objects));// $ids will now be an array of ['_id']s?>

But this is not very efficient: two cycles instead of one. Another solution is to use foreach: one cycle and a lot of freedom (and in the same scope).

erik dot stetina at gmail dot com (2011-09-27 03:05:01)

function to prefix given string to each element of an array:

{$callback=create_function('$str','return "'.$prefix.'".$str;');

returnarray_map($callback,$array);

}?>

usage:

$dir="./css/";$files=scandir($dir);$files=array_prefix_values($dir,$files);print_r($files);?>

output:

(

[0] => ./css/.

[1] => ./css/..

[2] => ./css/default.css

[4] => ./css/helper.css

[6] => ./css/page_layout.css

)

spark at limao dot com dot br (2011-09-08 07:48:09)

it's a usefull way to filter user input through get and post request arrays:

$get=array_map("addslashes",$_GET);?>

gordon dot mcvey at ntlworld dot com (2011-01-28 05:11:42)

You can use array_map with PHP native functions as well as user functions.  This is very handy if you need to sanitize arrays.

$integers=array_map('intval',$integers);$safeStrings=array_map('mysql_real_escape_string',$unsafeStrings);?>

pike-php at kw dot nl (2011-01-11 06:04:59)

If you're looking for a way to flatten multimaps, look at this:

$multimap= array(

array("name"=>"value1"),

array("name"=>"value2"),

array("name"=>"value3")

);$flatmap=array_map("array_pop",$multimap);print_r($flatmap);?>

Output:

Array

(

[0] => value1

[1] => value2

[2] => value3

)

brendan DOT caffrey AT me DOT com (2010-07-10 15:42:31)

Something that had me confused:

classCallback{

static functionadd($a) { return$a+1; }

}$array= array(0,1,2);array_map(array('Callback','add'),$array);// will not work, even though you're calling this in the test namespacearray_map(array('test\Callback','add'),$array);// will work?>

virtual dot greg at gmail dot com (2010-03-05 03:07:35)

PHP 5.3 enables us to use inline anonymous functions with array_map, cleaning up the syntax slightly.

$data= array(

array('id'=>1,'name'=>'Bob','position'=>'Clerk'),

array('id'=>2,'name'=>'Alan','position'=>'Manager'),

array('id'=>3,'name'=>'James','position'=>'Director')

);$names=array_map(

function($person) { return$person['name']; },$data);print_r($names);?>

This was possible (although not recommended) in prior versions of PHP 5, via create_function().

$names=array_map(create_function('$person','return $person["name"];'),$data);?>

You're less likely to catch errors in the latter version because the code is passed as string arguments.

These are alternatives to using a foreach:

$names= array();

foreach ($dataas$row) {$names[] =$row['name'];

}?>

kelly m (2010-02-17 14:28:28)

I realize this function is easy enough to make, but this is a faster version (twice the speed) of [a function] which I find incredibly useful.

if (is_array($key) || !is_array($input)) return array();$array= array();

foreach($inputas$v) {

if(array_key_exists($key,$v))$array[]=$v[$key];

}

return$array;

}?>

Usage:

onassar at gmail dot com (2009-10-13 19:06:13)

Fixed a bug with array recursion.

* arrayMap function. Customized array_map function which preserves keys/associate array indexes. Note that this costs a descent amount more memory (eg. 1.5k per call)

*

* @access public

* @param callback $callback Callback function to run for each element in each array.

* @param mixed $arr1 An array to run through the callback function.

* @param array $array Variable list of array arugments to run through the callback function.

* @return array Array containing all the elements of $arr1 after applying the callback function to each one, recursively, maintain keys.

*/functionarrayMap($callback,$arr1) {$results=    array();$args=    array();

if(func_num_args()>2)$args=    (array)array_shift(array_slice(func_get_args(),2));

foreach($arr1as$key=>$value) {$temp=$args;array_unshift($temp,$value);

if(is_array($value)) {array_unshift($temp,$callback);$results[$key]    =call_user_func_array(array('self','arrayMap'),$temp);

} else {$results[$key]    =call_user_func_array($callback,$temp);

}

}

return$results;

}?>

onassar at gmail dot com (2009-10-11 15:33:07)

Wrote up my own key preservation function for array mapping. It allows n arguments to be passed, and should be easy enough to follow if you need to make any mods. If you've got any thoughts let me know.

* arrayMap function. Customized array_map function which preserves keys/associate array indexes.

*

* @access public

* @param callback $callback Callback function to run for each element in each array.

* @param mixed $arr1 An array to run through the callback function.

* @param array $array Variable list of array arugments to run through the callback function.

* @return array Array containing all the elements of $arr1 after applying the callback function to each one, recursively, maintain keys.

*/functionarrayMap($callback,$arr1) {$results=    array();$args=    array();

if(func_num_args()>2)$args=    (array)array_shift(array_slice(func_get_args(),2));

foreach($arr1as$key=>$value) {

if(is_array($value)) {array_unshift($args,$value);array_unshift($args,$callback);$results[$key]    =call_user_func_array(array('self','arrayMap'),$args);

}

else {array_unshift($args,$value);$results[$key]    =call_user_func_array($callback,$args);

}

}

return$results;

}?>

macnimble at gmail dot com (2009-09-10 12:27:49)

I recently discovered that PHP has no loop-free manner for modifying the keys in an array. I was hoping to use a built-in function to prefix the keys.

Having found no native function to do this, I threw together this monster:

{$args=func_get_args();$prefix=array_shift($args);$func=create_function('$p,$k','return "$p{$k}";');

foreach ($argsAS$key=>$array):$args[$key] =array_combine(array_map($func,array_fill(0,count($array),$prefix)

,array_keys($array)

)

,array_values($array)

);

endforeach;

return$args;

}$array1= array('id'=>1,'title'=>'about-us','author'=>'Bill Brown','dated'=>'2009-SEP-15');$array2= array('id'=>2,'title'=>'about-them','author'=>'Bill Smith','dated'=>'2010-SEP-15');

echo'

',print_r($array1,1),print_r($array2,1),'
';$array=array_prefix_keys("content_",$array1,$array2);$array1=$array[0];$array2=$array[1];

echo'

',print_r($array1,1),print_r($array2,1),'
';?>

This will produce the following output:

Array

(

[id] => 1

[title] => about-us

[author] => Bill Brown

[dated] => 2009-SEP-15

)

Array

(

[id] => 2

[title] => about-them

[author] => Bill Smith

[dated] => 2010-SEP-15

)

Array

(

[content_id] => 1

[content_title] => about-us

[content_author] => Bill Brown

[content_dated] => 2009-SEP-15

)

Array

(

[content_id] => 2

[content_title] => about-them

[content_author] => Bill Smith

[content_dated] => 2010-SEP-15

)

Hope it helps!

Bill

[EDIT BY danbrown AT php DOT net: The original function and note was removed in favor of this update by the original author.  The original note also contained the following descriptive text.]

I recently discovered that PHP has no loop-free manner for modifying the keys in an array. I was hoping to use a built-in function to prefix the keys.

Having found no native function to do this, I threw together this monster.

ethaizone at hotmail dot com (2009-09-01 19:34:14)

My English is weak but I want to share my code.

I want to change formation of array but when I use null is callback function in array_map().

It has problem in result so I write new small function for it.

foreach($arras$k=>$v)

foreach($vas$k2=>$v2)$new_arr[$k2][$k] =$v[$k2];

return$new_arr;

}?>

Input:

Array

(

[Human] => Array

(

[0] => 1

[1] => 2

[2] => 3

[3] => 4

)

[Pet] => Array

(

[0] => Cat

[1] => Dog

[2] => Rabbit

[3] => Rat

)

)

OutPut:

Array

(

[0] => Array

(

[Human] => 1

[Pet] => Cat

)

[1] => Array

(

[Human] => 2

[Pet] => Dog

)

[2] => Array

(

[Human] => 3

[Pet] => Rabbit

)

[3] => Array

(

[Human] => 4

[Pet] => Rat

)

)

I hope it can useful.

galenjr at gmail dot com (2009-06-14 23:19:50)

Another way to array_map htmlentities with a specific quote style is to create a function that does it and map that function

returnhtmlentities($str,ENT_QUOTES);

}$good_array=array_map('map_entities',$bad_array);?>

radist-hack at yandex dot ru (2008-11-01 13:37:35)

To transpose rectangular two-dimension array, use the following code:

array_unshift($array, null);

$array = call_user_func_array("array_map", $array);

If you need to rotate rectangular two-dimension array on 90 degree, add the following line before or after (depending on the rotation direction you need) the code above:

$array = array_reverse($array);

Here is example:

$a= array(

array(1,2,3),

array(4,5,6));array_unshift($a,null);$a=call_user_func_array("array_map",$a);print_r($a);?>

Output:

Array

(

[0] => Array

(

[0] => 1

[1] => 4

)

[1] => Array

(

[0] => 2

[1] => 5

)

[2] => Array

(

[0] => 3

[1] => 6

)

)

Heero (2008-10-16 10:02:57)

You can easily remove all HTML tags from $_GET or $_POST variables using something like this:

$_POST=array_map('strip_tags',$_POST);$_GET=array_map('strip_tags',$_GET);?>

This is useful when you don't want to parse HTML.

stijnleenknegt at gmail dot com (2008-07-22 16:17:11)

If you want to pass an argument like ENT_QUOTES to htmlentities, you can do the follow.

$array=array_map('htmlentities',$array,array_fill(0,count($array) ,ENT_QUOTES) );?>

The third argument creates an equal sized array of $array filled with the parameter you want to give with your callback function.

GUI (2008-06-26 07:48:36)

The following takes an array of objects, and returns the result of calling a member function on each object. So if I have an array of objects that all have a getName() method, calling array_map_objects("getName", $thingies) will return the array filled with the getName() value for each object.

if(is_string($member_function) &&is_array($array)) {$callback=create_function('$e','return call_user_func(array($e, "'.$member_function.'"));');$values=array_map($callback,$array);

}

return$values;

}?>

BloodElf (2008-04-27 06:32:13)

Here is a simple way to highlight the matched words in the search results:

static$num=1;

return''.$word.'';

}$text="ala bala nica turska panica";$search="bala turska";$words=explode(' ',$search);

echostr_replace($words,array_map("highlight",$words),$text);

moester at gmail dot com (2008-04-02 13:21:38)

Wish this was built in.  Mimics Ruby and Prototype's array pluck function.  Returns specific key/column from an array of objects.

{

if (is_array($key) || !is_array($array)) return array();$funct=create_function('$e','return is_array($e) && array_key_exists("'.$key.'",$e) ? $e["'.$key.'"] : null;');

returnarray_map($funct,$array);

}// usage:$a= array(array("id"=>10,"name"=>"joe"), array("id"=>11,"name"=>"bob"));$ids=array_pluck("id",$a);// == array(10,11)$names=array_pluck("name",$a);// == array("joe", "bob")

//works on non-keyed arrays also:$a= array(array(3,4), array(5,6));$col2=array_pluck(1,$a);// == array(4,6) (grab 2nd column of data)?>

chreekat (2008-03-12 15:48:54)

I was miffed that array_map didn't have a way to pass values *and* keys to the callback, but then I realized I could do this:

function callback($k, $v) { ... }

array_map( "callback", array_keys($array), $array);

jo at ho dot nl (2008-02-17 14:10:46)

Could also use things like...

array_keys(); and array_values(); offcourse...

However it's just an example off recursion via this function..

Which I found pretty handy at times dealing with arrays..

could also use:

call_user_func(array($this,__FUNCTION),$args);?>

or

call_user_fuc_array(array($this,__FUNCTION__),$array);?>

or

public function__construct($arg){

if(is_array($arg)){

newself($arg);

}

else{

echo$arg.'
'.PHP_EOL;

}

}

}?>

Anyway.. plenty off examples..

It was just an idea for others...

avartabedian at webservice dot com dot uy (2008-02-08 05:39:36)

loaded67 at hotmail dot com, there is a little error in the add func params values.

Warning: Missing argument 2 for test::add(), called in /tmp/test.php on line 34 and defined in /tmp/test.php on line 6

Array => 

now it runs...

}/* procedural */else{

echo$key.' => '.$value.'
'.PHP_EOL;// do stuff...

// if(!isset($this->container[$key])){

//       $this->container[$key] = $value;

// }

//else{  // trigger_error() xor throw new Exception?

//         echo 'allready exists!
'.PHP_EOL;

//}}

}

}//$array= array ('one'=>'value1','two'=>'value2','three'=>'value3');$t= newtest;$t->add($array);?>

good luck!

loaded67 at hotmail dot com (2008-02-08 02:59:23)

this function is really nice for recursion in php!!!

example in a class:

}/* procedural */else{

echo$key.' => '.$value.'
'.PHP_EOL;// do stuff...

// if(!isset($this->container[$key])){

//       $this->container[$key] = $value;

// }

//else{  // trigger_error() xor throw new Exception?

//         echo 'allready exists!
'.PHP_EOL;

//}}

}

}//$array= array ('one'=>'value1','two'=>'value2','three'=>'value3');$t= newtest;$t->add($array);?>

you could easiely do this without a class too offcourse!

used in php 5.2.5

pmf (2008-01-22 19:02:13)

This function behaves exactly like array_map but additionally does not reject non-array arguments. Instead, it transforms them with the array_fill function to a constant valued array of required length according to the other array arguments (if any) and executes the original array_map function.

returncall_user_func_array("array_map",$args);

}?>

Example:

$get="first=value1&second=value2&third=value3";print_r(array_map2("explode","=",explode("&",$get)));?>

would print out:

(

[0] => Array

(

[0] =>first[1] =>value1)

[1] => Array

(

[0] =>second[1] =>value2)

[2] => Array

(

[0] =>third[1] =>value3)

)?>

/pmf

henrique at webcoder dot com dot br (2007-11-01 08:02:18)

Adding method support to function by Andref (multidimensionalArrayMap).

function array_map_r( $func, $arr )

{

$newArr = array();

foreach( $arr as $key => $value )

{

$newArr[ $key ] = ( is_array( $value ) ? array_map_r( $func, $value ) : ( is_array($func) ? call_user_func_array($func, $value) : $func( $value ) ) );

}

return $newArr;

}

array_map_r('function', array());

or

array_map_r(array('class', 'method'), array());

bturchik at iponweb dot net (2007-07-19 07:46:15)

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 (2006-10-24 12:14:17)

A recursive way to handle multidimensional arrays:

{$newArr= array();

foreach($arras$key=>$value)

{$newArr[$key] = (is_array($value) ?multidimensionalArrayMap($func,$value) :$func($value) );

}

return$newArr;

}?>

pcdinh at phpvietnam dot net (2006-03-17 20:50:57)

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.

(2005-08-26 06:57:43)

Here's a function, very helpfull to me, that allows you to map your callback on mixed args.

<?phpfunctionarray_smart_map ($callback) {// Initialization$args=func_get_args() ;array_shift($args) ;// suppressing the callback$result= array() ;// Validating parametersforeach($argsas$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 arrayif(!isset($size)) {$keys=array_keys($arg) ;$size=count($arg) ;// the others arrays must have the same dimension} elseif(count($arg) !=$size) {

returnFALSE;

}// all keys are suppressed$args[$key] =array_values($arg) ;

}// doing the callback thingif(!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

foreach($argsas$arg)$column[] = (is_array($arg) ?$arg[$i] :$arg) ;$result[$keys[$i]] =call_user_func_array($callback,$column) ;

}

return$result;

}?>

Trying with :

Returns :

array(

[foo] => array(

0 => bar1

1 => bar2

2 => bar3

)

[bar] => array(

1 => foo1

)

)

david dot tulloh at infaze dot com dot au (2005-07-06 16:53:52)

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 (2005-03-23 05:31:01)

The following function does exaclty the same thing of array_map. However, maintains the same index of the input arrays

{$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($param2as$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($param2as$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 (2005-02-19 23:29:40)

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 (2004-07-02 04:42:52)

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 (2004-04-09 17:07:03)

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:

foreach (array_keys($arrays) as$arrayKey) {$newArray= array ();

foreach ($indexesas$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 (2003-01-06 22:02:12)

A note when doing something allong the lines of:

var$var;

functionbar() {array_map(array($this,"baz"), array(1,2,3));

}

functionbaz($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 (2002-06-14 22:07:08)

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)

}

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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值