note 106866 deleted from function.array-map by danbrown
| From: | danbrown@php.net | Date: | Tue, 03 Jan 2012 22:13:19 +0000 |
| Subject: | note 106866 deleted from function.array-map by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-185336@lists.php.net to get a copy of this message | ||
Note Submitter: hornetbzz at free dot fr
----
I needed to enlarge the use of array_map based on erik dot stetina at gmail dot com example, eg to
add a suffix or a prefix string to multidimensional arrays with unknown structure.
<?php
class Tools {
/**
* Add recursively a suffix or a prefix string to all of the (assoc) array values
* Created 13/12/2011
* @see http://www.php.net/manual/en/function.array-map.php#105942
*/
static function array_mod_values_recurse($string, $position="suffix", array $array)
{
switch ($position) {
case "suffix":
$callback = create_function('$str', 'return $str. "'. $string .
'";' );
break;
case "prefix":
$callback = create_function('$str','return
"'.$string.'".$str;');
break;
default:
$callback = create_function('$str', 'return $str. "'. $string .
'";' );
break;
}
foreach ($array as $key => $value) {
if (is_array($value)){
$result[] = Tools::array_mod_values_recurse($string, $position, $value);
} else {
$result[] = array_map($callback, $array);
}
}
return $result;
}
}
?>
Usage example:
<?php
$txtbox = array(
array("FR"=> "Prénom", "EN"=> "First Name",
"IT"=> "Nome"),
array("FR"=> "Nom", "EN"=> "Name", "IT"=>
"Cognome"));
$string = " : ";
$position ="suffix";
$txtbox = Tools::array_mod_values_recurse($string, $position, $txtbox);
// DEBUG
echo '<br/>RESULT<pre>'; print_r($txtbox);echo '</pre>';
?>