Reply to Re: Replacing key in associative array

Your name:

Reply:


Posted by Christoph Burschka on 02/01/07 13:20

David Smithz schrieb:
> "Geoff Berrow" <blthecat@ckdog.co.uk> wrote in message
> news:<0r8ur2p751ajikm57gh5avfc05cahbci2e@
>
>
>
>>It's difficult to advise without knowing exactly what you want to do but
>
>
>>you could make a copy of the array changing the keys as necessary.
>
>>foreach($array as $key=>$value){
>> if($key=="key2"){
>> $key="key number 2";
>> }
>>$temparray[$key]=$value;
>>}
>>$array=$temparray;
>

Actually, I think this approach might be the most elegant and still
keeping the previous order. It assumes that there is an array $replace,
which maps the current key to the one it should be replaced with.

$keys=array_keys($array); // extract keys
$values=array_values($array); // extract values
foreach ($keys as $i=>$key) $keys[$i]=$replace[$key]; // replace
$array=array_combine($keys,$values); // map back together

This is just off the top of my head and untested - it should work
according to what I read on the php.net pages, but I haven't tried it out.

array_keys and array_values maintains the current order of the array,
however, so the keys should be mapped to the same values as before.

--
CB

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация