|
Posted by michael on 10/05/07 06:17
On Oct 4, 11:51 pm, "Marc Bauer" <marc....@gmx.net> wrote:
> Hi
>
> i'd like to replace an array key, but i cannot figure out how this could
> work.
>
> As an example this array:
>
> $array1 = array('key1' => 'value1', 'key2' => 'value2', 'key3' =>
> 'value3' );
>
> Now, i'd like to replace the 'key2' => 'value2' with 'key4' => 'value4' and
> the array should look like:
>
> $array1 = array('key1' => 'value1', 'key4' => 'value4', 'key3' =>
> 'value3' );
>
> The order of the keys is important... so i must replace on the same array
> position.
>
> Regards
> Marc
Hi Marc,
I'm not quit sure why you wanne do this.
If the ordre is so importen, then a index's array would properly have
been better.
You said you like to replace key2 with key4, so what happends to
key2 ? do they switch place or is it deleted ?
If they switch place then this is the function for you
<?php
$ar = array('nr1'=>1,'nr2'=>2,'nr3'=>3,'nr4'=>4,'nr5'=>5);
print_r(shiftplace($ar,'nr2','nr5'));
function shiftplace($a,$key1,$key2){
if (!array_key_exists($key1,$a) && !array_key_exists($key2,$a))
return;
$search = array_flip(array_keys($a));
$key1_index= $search[$key2];
$key1_value = $a[$key1];
$key2_index= $search[$key1];
$key2_value = $a[$key2];
$i=0;
foreach($a as $key => $value){
if($i==$key1_index) $new[$key1] = $key1_value;
elseif($i==$key2_index) $new[$key2] = $key2_value;
else $new[$key] = $value;
$i++;
}
return $new;
}
?>
If you want to replace it and delete key2 then this is the function
for you.
<?php
$ar = array('nr1'=>1,'nr2'=>2,'nr3'=>3,'nr4'=>4,'nr5'=>5);
//replace nr2 with nr5 and remove nr2
print_r(replaceplace($ar,'nr2','nr5'));
function replaceplace($a,$key1,$key2){
if (!array_key_exists($key1,$a) && !array_key_exists($key2,$a))
return;
$search = array_flip(array_keys($a));
$key1_index= $search[$key2];
$key1_value = $a[$key1];
$key2_index= $search[$key1];
$key2_value = $a[$key2];
$i=0;
foreach($a as $key => $value){
if($i==$key2_index) $new[$key2] = $key2_value;
else $new[$key] = $value;
$i++;
}
return $new;
}
?>
I hope it's of some help to you.
//Michael
Navigation:
[Reply to this message]
|