37

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

Array
(
    [0] => Array
        (
            [fee_id] => 15
            [fee_amount] => 308.5
            [year] => 2009                
        )

    [1] => Array
        (
            [fee_id] => 14
            [fee_amount] => 308.5
            [year] => 2009

        )

)
stef
  • 25,579
  • 30
  • 103
  • 142
  • 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
  • possible duplicate of [In PHP, how do you change the key of an array element?](http://stackoverflow.com/questions/240660/in-php-how-do-you-change-the-key-of-an-array-element) – Oleg Oct 29 '14 at 09:54

10 Answers10

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

This should work

lamas
  • 4,458
  • 6
  • 36
  • 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,074
  • 14
  • 19
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,090
  • 8
  • 44
  • 56
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,721
  • 1
  • 16
  • 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
  • 12,988
  • 30
  • 88
  • 157
  • 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
  • 171
  • 1
  • 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,414
  • 1
  • 28
  • 33
-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
  • 3
    @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
  • 4
    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