note 56190 deleted from function.array-map by cmb

From: Date: Sun, 29 Dec 2019 10:32:45 +0000
Subject: note 56190 deleted from function.array-map by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-213687@lists.php.net to get a copy of this message
Note Submitter: ---- 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 ) )

« previous php.notes (#213687) next »