2

Given this array:

$list = array(
   'one' => array(
       'A' => 1,
       'B' => 100,
       'C' => 1234,
   ),
   'two' => array(
       'A' => 1,
       'B' => 100,
       'C' => 1234,
       'three' => array(
           'A' => 1,
           'B' => 100,
           'C' => 1234,
       ),
       'four' => array(
           'A' => 1,
           'B' => 100,
           'C' => 1234,
       ),
   ),
   'five' => array(
       'A' => 1,
       'B' => 100,
       'C' => 1234,
   ),
);

I need a function(replaceKey($array, $oldKey, $newKey)) to replace any key 'one', 'two', 'three', 'four' or 'five' with a new key independently of the depth of that key. I need the function to return a new array, with the same order and structure.

I already tried working with answers from this questions but I can't find a way to keep the order and access the second level in the array:

Changing keys using array_map on multidimensional arrays using PHP

Change array key without changing order

PHP rename array keys in multidimensional array

This is my attempt that doesn't work:

function replaceKey($array, $newKey, $oldKey){
   foreach ($array as $key => $value){
      if (is_array($value))
         $array[$key] = replaceKey($value,$newKey,$oldKey);
      else {
         $array[$oldKey] = $array[$newKey];    
      }

   }         
   return $array;   
}

Regards

Community
  • 1
  • 1
lan.w
  • 59
  • 2
  • 8
  • You should be able to use the method in the second question you linked. But you need to make a recursive version that searches each level. – Barmar Feb 04 '16 at 22:59

1 Answers1

7

This function should replace all instances of $oldKey with $newKey.

function replaceKey($subject, $newKey, $oldKey) {

    // if the value is not an array, then you have reached the deepest 
    // point of the branch, so return the value
    if (!is_array($subject)) return $subject;

    $newArray = array(); // empty array to hold copy of subject
    foreach ($subject as $key => $value) {

        // replace the key with the new key only if it is the old key
        $key = ($key === $oldKey) ? $newKey : $key;

        // add the value with the recursive call
        $newArray[$key] = replaceKey($value, $newKey, $oldKey);
    }
    return $newArray;
}
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • 1
    You have to change " ($key == $oldKey)" by "($key === $oldKey)" => triple equale, because when $key equale=0 it will be set "$newKey" and its not correct – Abdallah Arffak Jan 15 '18 at 11:53