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 .....? Commented 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. Commented 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. Commented Apr 3, 2024 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

Sign up to request clarification or add additional context in comments.

4 Comments

You probably want to make it foreach( array_keys($array) as $k) or foreach($array as $k=>$v)
This will change the order: new key will be at the end
Why don't use $v['fee_id'] instead of $array[$k] ['fee_id'] ?
Yfeizi,because that will only change the temporary variable $v, and we want to change the original array.
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);

Comments

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 Comments

Because it re-counts it every time?
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
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 Comments

You have to make $arr a reference, foreach (...as &$arr). Otherwise changes in $arr will not change $array.
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
0

This is the working solution, i tested it.

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

1 Comment

Note that using reference variables in a for loop like this could be a terrible idea. See stackoverflow.com/questions/3307409/…
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;

Comments

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);


   ?>

Comments

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);

Comments

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 Comment

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.
0

Multidimensional 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 defined 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']];

Comments

-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 Comments

This is a really tidy way of doing it. Is the performance good? I imagine its quick to work with strings in PHP.
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.
The advantage of this over the lamas' answer is that it keeps the array in the same order.
@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?
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'.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.