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

时间:2016-02-04 22:55:51

标签: 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)),用新密钥替换任何键'one','two','three','four'或'five',而不依赖于那把钥匙的深度。我需要函数返回一个新数组,其中相同顺序结构

我已经尝试过处理这些问题的答案,但我找不到在阵列中保持订单并访问第二级的方法:

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

此致

1 个答案:

答案 0 :(得分:2)

此功能应将$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;
}