Home » Php » PHP rename array keys in multidimensional array

PHP rename array keys in multidimensional array

Posted by: admin April 23, 2020 Leave a comment

Questions:

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

        )

)
How to&Answers:
foreach ( $array as $k=>$v )
{
  $array[$k] ['id'] = $array[$k] ['fee_id'];
  unset($array[$k]['fee_id']);
}

This should work

Answer:

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

Answer:

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

Answer:

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.

Answer:

This is the working solution, i tested it.

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

Answer:

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;

Answer:

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


   ?>

Answer:

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

Answer:

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

Answer:

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.