Jump to content

change key (name) in associative array?


Recommended Posts

In the array (shown below) I need to change the 'name'
of one of the (first level) keys.

In the example, I'd like to change the key 'Boat' to
'Ship' without changing the order of the array
entries.

['Car']['ID']='445';
['Car']['Color']='blue';
['Car']['Note']='needs work';
['Boat']['ID']='491';
['Boat']['Color']='green';
['Boat']['Note']='for sale';
['Plane']['ID']='420';
['Plane']['Color']='azure';
['Plane']['Note']='ready';

Thanks a billion!
Link to comment
Share on other sites

For all intensive purposes, an associative array doesn't have an order. That's why it's referenced by the "key" of the array.

You can do the following:
[code]
<?php

$ary['Car']['ID'] = '445';
$ary['Car']['Color'] = 'blue';
$ary['Car']['Note'] = 'needs work';
$ary['Boat']['ID'] = '491';
$ary['Boat']['Color'] = 'green';
$ary['Boat']['Note'] = 'for sale';
$ary['Plane']['ID'] = '420';
$ary['Plane']['Color'] = 'azure';
$ary['Plane']['Note'] = 'ready';

$ary['Ship']['ID'] = $ary['Boat']['ID'];
$ary['Ship']['Color'] = $ary['Boat']['Color'];
$ary['Ship']['Note'] = $ary['Boat']['Note'];

unset($ary['Boat']['ID']);
unset($ary['Boat']['Color']);
unset($ary['Boat']['Note']);
unset($ary['Boat']);

echo '<pre>', print_r($ary, TRUE), '</pre>';

?>
[/code]

However, the array will look like this:
[quote]
Array
(
    [Car] => Array
        (
            [ID] => 445
            [Color] => blue
            [Note] => needs work
        )

    [Plane] => Array
        (
            [ID] => 420
            [Color] => azure
            [Note] => ready
        )

    [Ship] => Array
        (
            [ID] => 491
            [Color] => green
            [Note] => for sale
        )

)
[/quote]

Which IMO is not wrong, since one can still access it using the 'Ship' key.

You might want to rethink what you're trying to do or how you're accessing the associative array.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.