Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace array keys with given respective keys

I have an array like below

$old = array(
       'a' => 'blah',
       'b' => 'key',
       'c' => 'amazing',
       'd' => array(
                0 => 'want to replace',
                1 => 'yes I want to'
              )
       );

I have another array having keys to replace with key information.

$keyReplaceInfoz = array('a' => 'newA', 'b' => 'newB', 'c' => 'newC', 'd' => 'newD');

I need to replace all keys of array $old with respective values in array $keyReplaceInfo.

Output should be like this

$old = array(
       'newA' => 'blah',
       'newB' => 'key',
       'newC' => 'amazing',
       'newD' => array(
                0 => 'want to replace',
                1 => 'yes I want to'
              )
       );

I had to do it manually as below. I am expecting better option. can anyone suggest better way to accomplish this?

$new = array();
foreach ($old as $key => $value)
{
     $new[$keyReplaceInfoz[$key]] = $value;
}

I know this can be more simpler.

like image 314
Maulik Vora Avatar asked Jul 30 '12 13:07

Maulik Vora


3 Answers

array_combine(array_merge($old, $keyReplaceInfoz), $old)

I think this looks easier than what you posed.

like image 156
Summoner Avatar answered Oct 15 '22 10:10

Summoner


array_combine(
    ['newKey1', 'newKey2', 'newKey3'],
    array_values(['oldKey1' => 1, 'oldKey2' => 2, 'oldKey3' => 3])
);

This should do the trick as long as you have the same number of values and the same order.

like image 28
Magarusu Avatar answered Oct 15 '22 12:10

Magarusu


IMO using array_combine, array_merge, even array_intersect_key is overkill. The original code is good enough, and very fast.

like image 43
Bohan Yang Avatar answered Oct 15 '22 12:10

Bohan Yang