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

标签 php arrays multidimensional-array replace key

给定这个数组:

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

我需要一个函数(replaceKey($array, $oldKey, $newKey)) 来替换任意键“一”、“二”、“三”、“四”或“五”与新键独立于该键的深度。我需要函数返回一个新数组,具有相同的顺序结构

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

Changing keys using array_map on multidimensional arrays using PHP

Change array key without changing order

PHP rename array keys in multidimensional array

这是我的尝试,但行不通:

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

问候

最佳答案

此函数应将 $oldKey 的所有实例替换为 $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;
}

关于php - 如何替换多维数组中的键并保持顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35213277/

相关文章:

php - array_splice() 用于关联数组

php - 遍历多维数组

php - 多维数组中特定键的数组差异

php - 如何将帖子从 wordpress 拉到不同主机上的其他非 wordpress 站点?

php - 使用 WHERE 子句将数组传递给查询

java - 带有数组名称的 playframework 表单输入

python - 在Python3中逐一读取列表的元素

c++ - C++中高效的多维数据存储

javascript - 仅从下拉列表中获取选定的值并从下拉列表中删除未选定的值

php - {${phpinfo()}} 叫什么? (远程命令执行相关)