note 56190 added to function.array-map
| From: | php-general at lists dot php dot net | Date: | Fri, 26 Aug 2005 13:57:43 +0000 |
| Subject: | note 56190 added to function.array-map | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-94221@lists.php.net to get a copy of this message | ||
Here's a function, very helpfull to me, that allows you to map your callback on mixed args.
<?php
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 :
<?php
// $_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
)
)
----
Manual Page -- http://www.php.net/manual/en/function.array-map.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+56190
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+56190&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+56190&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+56190&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+56190&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+56190&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+56190&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+56190&report=yes
Search -- http://master.php.net/manage/user-notes.php