300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > php array pluck PHP 将回调函数作用到给定数组的单元上

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

时间:2020-01-31 19:35:24

相关推荐

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

用户评论:

hrvoj3e at gmail dot com (-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 (-04-07 12:30:26)

EasywaytoconvertarrayintoUtf_8:

{

if(is_array($array))

{

returnarray_map("utf8_encode_clever",$array);

}

else

{

returnutf8_encode($array);

}

}//here,wewillcallourfunctiontoconvert$data:$data=utf8_encode_clever($data);?>

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

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

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

Whynotanarrayofcallbacks?

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 (-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 (-03-07 10:35:00)

Analternativeforrecursivemapping;

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

?array_map_recursive($fn,$v)

:$fn($v);//orcall_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

)

)

)

@mspreij (-02-26 22:48:19)

HopeI'mnotlatetotheparty,here'smyfunctiontoapplyarray_maptothe*keys*ofanarray.

Extraarrayargumentswillbeusedforthecallbackfunction'sparametersjustlikewitharray_map,withthedifferencethatastringisalsoallowed:itwilljustbeusedtocreateanarrayofappropriatelengthwithaseachvaluethatstring.Arraysareleftalone(andwillbepaddedwithnullsbyarray_mapasneeded).

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

if(!is_callable($callback))trigger_error("firstargument(callback)isnotavalidfunction",E_USER_ERROR);

if(!is_array($array))trigger_error("secondargumentmustbeanarray",E_USER_ERROR);$args[1]=array_keys($array);//Ifanyadditionalargumentsarenotarrays,assumethatvalueiswantedforevery$arrayitem.

//array_map()willpadshorterarrayswithNullvaluesfor($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);

}//Someexamples:$arr=array('foo'=>123,'bar'=>456);//simplyuppercasekeys: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)}

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

//Apartfromthe(staticstring)prefix,wealsonumberthem:$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 (-11-28 05:00:17)

Notethatthe$arrargumenthastobeanarray,notjustaTraversable/Iterator.

Forinstancethiswon'twork:

$documents=$mongo->db->collection->find();//$documentsisTraversablebyforeach$ids=array_map(function($document){

return$document['_id'];

},$objects);//$idswillnowbeNULL,because$documentswasn'tanArray?>

Asolutionistofirstuseiterator_to_array():

$ids=array_map(function($document){

return$document['_id'];

},iterator_to_array($objects));//$idswillnowbeanarrayof['_id']s?>

Butthisisnotveryefficient:twocyclesinsteadofone.Anothersolutionistouseforeach:onecycleandalotoffreedom(andinthesamescope).

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

functiontoprefixgivenstringtoeachelementofanarray:

{$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 (-09-08 07:48:09)

it'sausefullwaytofilteruserinputthroughgetandpostrequestarrays:

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

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

Youcanusearray_mapwithPHPnativefunctionsaswellasuserfunctions.Thisisveryhandyifyouneedtosanitizearrays.

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

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

Ifyou'relookingforawaytoflattenmultimaps,lookatthis:

$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 (-07-10 15:42:31)

Somethingthathadmeconfused:

classCallback{

staticfunctionadd($a){return$a+1;}

}$array=array(0,1,2);array_map(array('Callback','add'),$array);//willnotwork,eventhoughyou'recallingthisinthetestnamespacearray_map(array('test\Callback','add'),$array);//willwork?>

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

PHP5.3enablesustouseinlineanonymousfunctionswitharray_map,cleaningupthesyntaxslightly.

$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);?>

Thiswaspossible(althoughnotrecommended)inpriorversionsofPHP5,viacreate_function().

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

You'relesslikelytocatcherrorsinthelatterversionbecausethecodeispassedasstringarguments.

Thesearealternativestousingaforeach:

$names=array();

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

}?>

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

Irealizethisfunctioniseasyenoughtomake,butthisisafasterversion(twicethespeed)of[afunction]whichIfindincrediblyuseful.

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

foreach($inputas$v){

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

}

return$array;

}?>

Usage:

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

Fixedabugwitharrayrecursion.

*arrayMapfunction.Customizedarray_mapfunctionwhichpreserveskeys/associatearrayindexes.Notethatthiscostsadescentamountmorememory(eg.1.5kpercall)

*

*@accesspublic

*@paramcallback$callbackCallbackfunctiontorunforeachelementineacharray.

*@parammixed$arr1Anarraytorunthroughthecallbackfunction.

*@paramarray$arrayVariablelistofarrayarugmentstorunthroughthecallbackfunction.

*@returnarrayArraycontainingalltheelementsof$arr1afterapplyingthecallbackfunctiontoeachone,recursively,maintainkeys.

*/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 (-10-11 15:33:07)

Wroteupmyownkeypreservationfunctionforarraymapping.Itallowsnargumentstobepassed,andshouldbeeasyenoughtofollowifyouneedtomakeanymods.Ifyou'vegotanythoughtsletmeknow.

*arrayMapfunction.Customizedarray_mapfunctionwhichpreserveskeys/associatearrayindexes.

*

*@accesspublic

*@paramcallback$callbackCallbackfunctiontorunforeachelementineacharray.

*@parammixed$arr1Anarraytorunthroughthecallbackfunction.

*@paramarray$arrayVariablelistofarrayarugmentstorunthroughthecallbackfunction.

*@returnarrayArraycontainingalltheelementsof$arr1afterapplyingthecallbackfunctiontoeachone,recursively,maintainkeys.

*/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 (-09-10 12:27:49)

IrecentlydiscoveredthatPHPhasnoloop-freemannerformodifyingthekeysinanarray.Iwashopingtouseabuilt-infunctiontoprefixthekeys.

Havingfoundnonativefunctiontodothis,Ithrewtogetherthismonster:

{$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'=>'BillBrown','dated'=>'-SEP-15');$array2=array('id'=>2,'title'=>'about-them','author'=>'BillSmith','dated'=>'-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),'

';?>

Thiswillproducethefollowingoutput:

Array

(

[id]=>1

[title]=>about-us

[author]=>BillBrown

[dated]=>-SEP-15

)

Array

(

[id]=>2

[title]=>about-them

[author]=>BillSmith

[dated]=>-SEP-15

)

Array

(

[content_id]=>1

[content_title]=>about-us

[content_author]=>BillBrown

[content_dated]=>-SEP-15

)

Array

(

[content_id]=>2

[content_title]=>about-them

[content_author]=>BillSmith

[content_dated]=>-SEP-15

)

Hopeithelps!

Bill

[EDITBYdanbrownATphpDOTnet:Theoriginalfunctionandnotewasremovedinfavorofthisupdatebytheoriginalauthor.Theoriginalnotealsocontainedthefollowingdescriptivetext.]

IrecentlydiscoveredthatPHPhasnoloop-freemannerformodifyingthekeysinanarray.Iwashopingtouseabuilt-infunctiontoprefixthekeys.

Havingfoundnonativefunctiontodothis,Ithrewtogetherthismonster.

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

MyEnglishisweakbutIwanttosharemycode.

IwanttochangeformationofarraybutwhenIusenulliscallbackfunctioninarray_map().

IthasprobleminresultsoIwritenewsmallfunctionforit.

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

)

)

Ihopeitcanuseful.

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

Anotherwaytoarray_maphtmlentitieswithaspecificquotestyleistocreateafunctionthatdoesitandmapthatfunction

returnhtmlentities($str,ENT_QUOTES);

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

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

Totransposerectangulartwo-dimensionarray,usethefollowingcode:

array_unshift($array,null);

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

Ifyouneedtorotaterectangulartwo-dimensionarrayon90degree,addthefollowinglinebeforeorafter(dependingontherotationdirectionyouneed)thecodeabove:

$array=array_reverse($array);

Hereisexample:

$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 (-10-16 10:02:57)

YoucaneasilyremoveallHTMLtagsfrom$_GETor$_POSTvariablesusingsomethinglikethis:

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

Thisisusefulwhenyoudon'twanttoparseHTML.

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

IfyouwanttopassanargumentlikeENT_QUOTEStohtmlentities,youcandothefollow.

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

Thethirdargumentcreatesanequalsizedarrayof$arrayfilledwiththeparameteryouwanttogivewithyourcallbackfunction.

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

Thefollowingtakesanarrayofobjects,andreturnstheresultofcallingamemberfunctiononeachobject.SoifIhaveanarrayofobjectsthatallhaveagetName()method,callingarray_map_objects("getName",$thingies)willreturnthearrayfilledwiththegetName()valueforeachobject.

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

}

return$values;

}?>

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

Hereisasimplewaytohighlightthematchedwordsinthesearchresults:

static$num=1;

return''.$word.'';

}$text="alabalanicaturskapanica";$search="balaturska";$words=explode('',$search);

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

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

Wishthiswasbuiltin.MimicsRubyandPrototype'sarraypluckfunction.Returnsspecifickey/columnfromanarrayofobjects.

{

if(is_array($key)||!is_array($array))returnarray();$funct=create_function('$e','returnis_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")

//worksonnon-keyedarraysalso:$a=array(array(3,4),array(5,6));$col2=array_pluck(1,$a);//==array(4,6)(grab2ndcolumnofdata)?>

chreekat (-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 (-02-17 14:10:46)

Couldalsousethingslike...

array_keys();andarray_values();offcourse...

Howeverit'sjustanexampleoffrecursionviathisfunction..

WhichIfoundprettyhandyattimesdealingwitharrays..

couldalsouse:

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

or

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

or

publicfunction__construct($arg){

if(is_array($arg)){

newself($arg);

}

else{

echo$arg.'

'.PHP_EOL;

}

}

}?>

Anyway..plentyoffexamples..

Itwasjustanideaforothers...

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

loaded67athotmaildotcom,thereisalittleerrorintheaddfuncparamsvalues.

Warning:Missingargument2fortest::add(),calledin/tmp/test.phponline34anddefinedin/tmp/test.phponline6

Array=>

nowitruns...

}/*procedural*/else{

echo$key.'=>'.$value.'

'.PHP_EOL;//dostuff...

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

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

//}

//else{//trigger_error()xorthrownewException?

//echo'allreadyexists!

'.PHP_EOL;

//}}

}

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

goodluck!

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

thisfunctionisreallyniceforrecursioninphp!!!

exampleinaclass:

}/*procedural*/else{

echo$key.'=>'.$value.'

'.PHP_EOL;//dostuff...

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

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

//}

//else{//trigger_error()xorthrownewException?

//echo'allreadyexists!

'.PHP_EOL;

//}}

}

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

youcouldeasielydothiswithoutaclasstoooffcourse!

usedinphp5.2.5

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

Thisfunctionbehavesexactlylikearray_mapbutadditionallydoesnotrejectnon-arrayarguments.Instead,ittransformsthemwiththearray_fillfunctiontoaconstantvaluedarrayofrequiredlengthaccordingtotheotherarrayarguments(ifany)andexecutestheoriginalarray_mapfunction.

returncall_user_func_array("array_map",$args);

}?>

Example:

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

wouldprintout:

(

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

Arecursivewaytohandlemultidimensionalarrays:

{$newArr=array();

foreach($arras$key=>$value)

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

}

return$newArr;

}?>

pcdinh at phpvietnam dot net (-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.

(-08-26 06:57:43)

Here'safunction,veryhelpfulltome,thatallowsyoutomapyourcallbackonmixedargs.

<?phpfunctionarray_smart_map ($callback){//Initialization$args=func_get_args();array_shift($args);//suppressingthecallback$result=array();//Validatingparametersforeach($argsas$key=>$arg)

if(is_array($arg)){//thefirstarrayfoundgivesthesizeofmappingandthekeysthatwillbeusedfortheresultingarrayif(!isset($size)){$keys=array_keys($arg);$size=count($arg);//theothersarraysmusthavethesamedimension}elseif(count($arg)!=$size){

returnFALSE;

}//allkeysaresuppressed$args[$key]=array_values($arg);

}//doingthecallbackthingif(!isset($size))//ifnoarrayswerefound,returnstheresultofthecallbackinanarray$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;

}?>

Tryingwith:

Returns:

array(

[foo]=>array(

0=>bar1

1=>bar2

2=>bar3

)

[bar]=>array(

1=>foo1

)

)

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

Youcanpassvaluestoarray_mapbyreference,essentiallyallowingyoutouseitasyouwouldarray_walkwithmultiplearraysasparameters.

Atrivialexample:

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

Thefollowingfunctiondoesexacltythesamethingofarray_map.However,maintainsthesameindexoftheinputarrays

{$res=array();

if($param3!==NULL)

{

foreach(array(2,3)as$p_name)

{

if(!is_array(${'param'.$p_name}))

{trigger_error(__FUNCTION__.'():Argument#'.$p_name.'shouldbeanarray',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#2shouldbeanarray',E_USER_WARNING);

return;

}

foreach($param2as$key=>$val)

{$res[$key]=call_user_func($param1,$param2[$key]);

}

}

return$res;

}?>

Forinstance:

$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);?>

Theresultwillbe:

Array

(

[3]=>ad

[4]=>be

[5]=>cf

)

endofyourself at yahoo dot com (-02-19 23:29:40)

Ifyouneedtocallastaticmethodfromarray_map,thiswillNOTwork:

array_map('myclass::myMethod',$value);?>

Instead,youneedtodothis:

array_map(array('myclass','myMethod'),$value);?>

ItishelpfultorememberthatthiswillworkwithanyPHPfunctionwhichexpectsacallbackargument.

nd0 at gmx dot de (-07-02 04:42:52)

array_mapworksalsofinewithcreate_function:

$a=array(1,2,3,4,5);$b=array_map(create_function('$n','return$n*$n*$n;'),$a);print_r($b);?>

ifyouwanttomanipulatetheelementsofthearray,insteadtoonacopy,

thantakealookatarray_walk:

$a=array(1,2,3,4,5);array_walk($a,create_function('&$n','$n=$n*$n*$n;'));print_r($a);?>

TheResultofbothis:

Array

(

[0]=>1

[1]=>8

[2]=>27

[3]=>64

[4]=>125

)

bishop (-04-09 17:07:03)

Occasionally,youmayfindthatyouneedtopulloutacolumn(orseveral)fromanarray.Here'samap-likefunctiontodothat:

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,doingthis:

$t1=array(2=>array('a','b','c'),1=>array('d','e','f'),5=>array('g','h','i'),

);$t2=array_shear($t1,1,0);?>

willresultin:

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

Anotewhendoingsomethingallongthelinesof:

var$var;

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

}

functionbaz($arg){$this->var=$this->var+$arg;

}

}?>

Thiswill*not*workasexpected.Youneedtopass$thisbyreferenceaswith:

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

oryou'llbemakingacopyoftheobjecteachtime,changingavalue,thenthrowingtheresultaway.

dan at mojavelinux dot com (2002-06-14 22:07:08)

Hereisabetter,moretrueversionofadeeparray_map.Theonlynegativeofthisfunctionisthatthearrayispassedbyreference,sojustbeawareofthat.(patcheswelcome)

}

foreach(array_keys($in_array)as$key){//weneedareference,notacopy,normalforeachwon'tdo$value=&$in_array[$key];//weneedtocopyargsbecausewearedoing

//manipulationonitfartherdown$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;

}?>

Thisisaneatfunctionbecauseyoucanpassanarray,afunction,andanarrayofparameters,andfinally,andindexofwhereinthearrayofparametersforthecallbackfunctionthecontentsyouaremappingshouldgetreplaced.Thisindexishumanbased(startsat1),andcanbeusedinsomethinglikeapreg_replacecallback,wherethecontentsmustbethe3rdindex.Enjoy!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。