note 93413 deleted from function.array-map by thiago

From: Date: Thu, 10 Sep 2009 19:34:33 +0000
Subject: note 93413 deleted from function.array-map by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-160433@lists.php.net to get a copy of this message
Note Submitter: macnimble at gmail dot com ---- 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: <?php function array_prefix_keys ( $a = array() , $p = ':' ) { return array_combine( array_map( create_function('$k,$p','return "$p{$k}";') , array_keys($a) , array_fill(0,count($a),$p) ) , array_values($a) ); } ?> It isn't very pretty, to be sure, but it does allow you to do this: <?php $array = array( 'id' => 1, 'title' => 'about-us', 'author' => 'Bill Brown', 'dated' => '2009-SEP-15' ); echo '<pre>',print_r($array,1),'</pre>'; $array = array_prefix_keys($array,"content_"); echo '<pre>',print_r($array,1),'</pre>'; ?> Which will give you this: Array ( [id] => 1 [title] => about-us [author] => Bill Brown [dated] => 2009-SEP-15 ) Array ( [content_id] => 1 [content_title] => about-us [content_author] => Bill Brown [content_dated] => 2009-SEP-15 ) Hope it helps! --Bill

« previous php.notes (#160433) next »