如何替换多维数组中的键并保持顺序

lan*_*n.w 2 php arrays replace key multidimensional-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,
   ),
);
Run Code Online (Sandbox Code Playgroud)

我需要一个函数( replaceKey($array, $oldKey, $newKey)) 用一个新键替换任何键“一”、“二”、“三”、“四”或“五”,而与该的深度无关。我需要该函数返回一个具有相同 orderstructure的新数组。

我已经尝试使用这些问题的答案,但我找不到一种方法来保持顺序并访问数组中的第二级

使用 PHP 在多维数组上使用 array_map 更改键

更改数组键而不更改顺序

PHP重命名多维数组中的数组键

这是我行不通的尝试:

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;   
}
Run Code Online (Sandbox Code Playgroud)

问候

Don*_*nic 6

此函数应替换$oldKeywith 的所有实例$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;
}
Run Code Online (Sandbox Code Playgroud)