PHP switch two array keys

I have an array:

$array['text6'] = array(
    'elem2' => 'text2',
    'elem3' => 'text3',
    'elem4' => 'text4',
    'elem5' => 'text5'
    'elem6' => 'text6'
);

And I would like to change, for example, text6 with a different key as follows:

$name_key = 'elem4';

// something action here
// and final array:

    $array['text4'] = array(
        'elem2' => 'text2',
        'elem3' => 'text3',
        'elem5' => 'text5'
        'elem6' => 'text6'
    );

How can i do this? I have 105 arrays, and I need to change each array in the same way, so when the array looks like this:

$array['text6'] = array(
    'elem2' => 'text2',
    'elem3' => 'text3',
    'elem4' => 'text4',
    'elem5' => 'text5'
    'elem6' => 'text6'
);

$array['othertext6'] = array(
    'elem2' => 'othertext2',
    'elem3' => 'othertext3',
    'elem4' => 'othertext4',
    'elem5' => 'othertext5'
    'elem6' => 'othertext6'
);

And I would like to change the main key with key number three (key β†’ 'elem4'), it should do it in each array (different beetwen arrays are only in value, the keys are always the same):

$name_key = 'elem4';

// action...

$array['text4'] = array(
    'elem2' => 'text2',
    'elem3' => 'text3',
    'elem5' => 'text5'
    'elem6' => 'text6'
);

$array['othertext4'] = array(
    'elem2' => 'othertext2',
    'elem3' => 'othertext3',
    'elem5' => 'othertext5'
    'elem6' => 'othertext6'
);

How can i do this?

+4
source share
1 answer

, , . , .

?

, "elem4" , ?

, :

, .

$list = array($array['text4'], $array['text5'], ... (all your other arrays here));

$name_key = 'elem4';
foreach ($list as $k => $v) {
   $new_key =  $v[$name_key];
   unset ($v[$name_key]);
   $list[$new_key] = $v;
   unset ($list[$k]);
}
+2

Source: https://habr.com/ru/post/1621649/


All Articles