40

In an array such as the one below, how could I rename "fee_id" to "id"?

Input array:

[
    ['fee_id' => 15, 'fee_amount' => 308.5, 'year' => 2009],
    ['fee_id' => 14, 'fee_amount' => 308.5, 'year' => 2009],
]

Expected result:

[
    ['id' => 15, 'fee_amount' => 308.5, 'year' => 2009],
    ['id' => 14, 'fee_amount' => 308.5, 'year' => 2009],
]
3
  • 10
    Is this data coming from a database? Could you change the query? SELECT fee_id as id, fee_amount as amount, year FROM .....?
    – gnarf
    Feb 6, 2010 at 11:56
  • yes but this array and the query that gens it is used all over the app and its easier to just change the output in one place.
    – stef
    Feb 6, 2010 at 13:28
  • Very related Change keys in each row of a 2d array without losing values but not quite a duplicate. Apr 3 at 19:43

11 Answers 11

46
foreach ( $array as $k=>$v )
{
  $array[$k] ['id'] = $array[$k] ['fee_id'];
  unset($array[$k]['fee_id']);
}

This should work

4
  • 2
    You probably want to make it foreach( array_keys($array) as $k) or foreach($array as $k=>$v)
    – gnarf
    Feb 6, 2010 at 11:53
  • 7
    This will change the order: new key will be at the end
    – Oleg
    Oct 29, 2014 at 9:53
  • 1
    Why don't use $v['fee_id'] instead of $array[$k] ['fee_id'] ?
    – YFeizi
    Feb 15, 2015 at 8:21
  • Yfeizi,because that will only change the temporary variable $v, and we want to change the original array.
    – pbarney
    Jun 19, 2020 at 21:28
19

You could use array_map() to do it.

$myarray = array_map(function($tag) {
    return array(
        'id' => $tag['fee_id'],
        'fee_amount' => $tag['fee_amount'],
        'year' => $tag['year']
    ); }, $myarray);
1
$arrayNum = count($theArray);

for( $i = 0 ; $i < $arrayNum ; $i++ )
{
    $fee_id_value = $theArray[$i]['fee_id'];
    unset($theArray[$i]['fee_id']);
    $theArray[$i]['id'] = $fee_id_value;
}

This should work.

2
  • Because it re-counts it every time?
    – Niels Bom
    Feb 6, 2010 at 11:56
  • Yep, assuming he has a big array this will count it every time and the page will load slower / the server load will go up
    – lamas
    Feb 6, 2010 at 11:59
0

Copy the current 'fee_id' value to a new key named 'id' and unset the previous key?

foreach ($array as $arr)
{
  $arr['id'] = $arr['fee_id'];
  unset($arr['fee_id']);
}

There is no function builtin doing such thin afaik.

2
  • 4
    You have to make $arr a reference, foreach (...as &$arr). Otherwise changes in $arr will not change $array.
    – VolkerK
    Feb 6, 2010 at 11:48
  • 3
    This does not work, the PHP manual says: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself
    – Niels Bom
    Feb 6, 2010 at 11:49
0

This is the working solution, i tested it.

foreach ($myArray as &$arr) {
    $arr['id'] = $arr['fee_id'];
    unset($arr['fee_id']);
}
1
0

The snippet below will rename an associative array key while preserving order (sometimes... we must). You can substitute the new key's $value if you need to wholly replace an item.

$old_key = "key_to_replace";
$new_key = "my_new_key";

$intermediate_array = array();
while (list($key, $value) = each($original_array)) {
  if ($key == $old_key) {
    $intermediate_array[$new_key] = $value;
  }
  else {
    $intermediate_array[$key] = $value;
  }
}
$original_array = $intermediate_array;
0

Converted 0->feild0, 1->field1,2->field2....

This is just one example in which i get comma separated value in string and convert it into multidimensional array and then using foreach loop i changed key value of array

<?php

    $str = "abc,def,ghi,jkl,mno,pqr,stu 
    abc,def,ghi,jkl,mno,pqr,stu
    abc,def,ghi,jkl,mno,pqr,stu
    abc,def,ghi,jkl,mno,pqr,stu;

    echo '<pre>';
    $arr1 = explode("\n", $str); // this will create multidimensional array from upper string
    //print_r($arr1);
    foreach ($arr1 as $key => $value) {
        $arr2[] = explode(",", $value);
        foreach ($arr2 as $key1 => $value1) {
            $i =0;
            foreach ($value1 as $key2 => $value2) { 
                $key3 = 'field'.$i;
                $i++;
                $value1[$key3] = $value2;
                unset($value1[$key2]);           
            }
        }
        $arr3[] = $value1;
    }
    print_r($arr3);


   ?>
0

I wrote a function to do it using objects or arrays (single or multidimensional) see at https://github.com/joaorito/php_RenameKeys.

Bellow is a simple example, you can use a json feature combine with replace to do it.

// Your original array (single or multi)

$original = array(
'DataHora'  => date('YmdHis'),
'Produto'   => 'Produto 1',
'Preco'     => 10.00,
'Quant'     => 2);

// Your map of key to change

$map = array(
'DataHora'  => 'Date',
'Produto'   => 'Product',
'Preco'     => 'Price',
'Quant'     => 'Amount');

$temp_array = json_encode($original);

foreach ($map AS $k=>$v) {
    $temp_array = str_ireplace('"'.$k.'":','"'.$v.'":', $temp);
    }

$new_array = json_decode($temp, $array);
0

Multidimentional array key can be changed dynamically by following function:

function change_key(array $arr, $keySetOrCallBack = []) 
{
    $newArr = [];

    foreach ($arr as $k => $v) {

        if (is_callable($keySetOrCallBack)) {
            $key = call_user_func_array($keySetOrCallBack, [$k, $v]);
        } else {
            $key = $keySetOrCallBack[$k] ?? $k;
        }

        $newArr[$key] = is_array($v) ? array_change_key($v, $keySetOrCallBack) : $v;
    }

    return $newArr;
}

Sample Example:

$sampleArray = [
    'hello' => 'world', 
    'nested' => ['hello' => 'John']
];

//Change by difined key set
$outputArray = change_key($sampleArray, ['hello' => 'hi']);
//Output Array: ['hi' => 'world', 'nested' => ['hi' => 'John']];

//Change by callback  
$outputArray = change_key($sampleArray, function($key, $value) {
      return ucwords(key);
});
//Output Array: ['Hello' => 'world', 'Nested' => ['Hello' => 'John']];
0

made a rename_keys function with optionally recursive support:

function rename_keys(array &$array, array $key_map, bool $recursive = false): void
{
    if ($recursive) {
        foreach ($array as &$value) {
            if (is_array($value)) {
                rename_keys($value, $key_map, true);
            }
        }
        unset($value);
    }
    foreach ($key_map as $old_key => $new_key) {
        if (array_key_exists($old_key, $array)) {
            $array[$new_key] = $array[$old_key];
            unset($array[$old_key]);
        }
    }
}

usage:

rename_keys($arr, ["fee_id" => "id"], true);
1
  • To clarify (because this answer doesn't include an explanation of how it works), the $key_map is expected to be a flat array. In other words, if you declare a multidimensional key map with the intention of synchronously traversing the levels between the original array and the key array, it won't satisfy. It should also be stated that modifying the input array directly may accidentally overwrite data if a new key matches an old key. To prevent key conflicts, write all of the new keys into a new array. This answer appears to be answering a different question where recursion is necessary. May 21, 2023 at 2:48
-3

I have been trying to solve this issue for a couple hours using recursive functions, but finally I realized that we don't need recursion at all. Below is my approach.

$search = array('key1','key2','key3');
$replace = array('newkey1','newkey2','newkey3');

$resArray = str_replace($search,$replace,json_encode($array));
$res = json_decode($resArray);

On this way we can avoid loop and recursion.

Hope It helps.

5
  • This is a really tidy way of doing it. Is the performance good? I imagine its quick to work with strings in PHP.
    – djskinner
    Aug 20, 2012 at 10:51
  • If you're rocking associative arrays, be sure to use json_decode's second param with Antonio's solution: $res = json_decode($resArray,true); Thanks, Antonio. I just joined SO just to upvote and "Yes!" this. Oct 23, 2012 at 20:30
  • The advantage of this over the lamas' answer is that it keeps the array in the same order.
    – Waggers
    Mar 26, 2013 at 11:14
  • 4
    @Antonio How do you make sure that only keys are affected and not values? Also if there are two keys like so Phone and Home Phone and $search = array('Phone', 'Home Phone') and $replace=array('Mobile', 'Work Mobile') then won't it replace Phone from both keys first and then when it will search for Work Phone then it wont find it becaue now the new key name will be Work Mobile.. makes sense?
    – Lucky Soni
    Apr 4, 2013 at 6:15
  • 5
    This also runs the risk of changing the values. If $array['key1'] = 'key1' then after it runs through this code it would be $array['newkey1'] = 'newkey1'. Jun 19, 2013 at 20:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.