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],
]
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
stef
  • 26,771
  • 31
  • 105
  • 143
  • 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 06 '10 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 06 '10 at 13:28

11 Answers11

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

This should work

lamas
  • 4,528
  • 7
  • 38
  • 43
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);
Ruslan Novikov
  • 1,320
  • 15
  • 21
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.

Niels Bom
  • 8,728
  • 11
  • 46
  • 62
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.

TheGrandWazoo
  • 2,879
  • 1
  • 17
  • 15
  • 4
    You have to make $arr a reference, `foreach (...as &$arr)`. Otherwise changes in $arr will not change $array. – VolkerK Feb 06 '10 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 06 '10 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']);
}
smartmouse
  • 13,912
  • 34
  • 100
  • 166
  • Note that using reference variables in a for loop like this could be a terrible idea. See http://stackoverflow.com/questions/3307409/php-pass-by-reference-in-foreach – Pang Aug 31 '16 at 07:03
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;
GabeSullice
  • 321
  • 2
  • 4
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);


   ?>
jaykishan
  • 1
  • 1
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']];
Mahbub
  • 4,812
  • 1
  • 31
  • 34
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);
hanshenrik
  • 19,904
  • 4
  • 43
  • 89
  • 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. – mickmackusa May 21 '23 at 02: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.

Antonio
  • 27
  • 1
  • 1
  • 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 '12 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. – Matthew Poer Oct 23 '12 at 20:30
  • The advantage of this over the lamas' answer is that it keeps the array in the same order. – Waggers Mar 26 '13 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 04 '13 at 06: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'`. – Scott Keck-Warren Jun 19 '13 at 20:02