如何替换多维数组中的键并保持顺序 [英] How to replace key in multidimensional array and maintain order

查看:124
本文介绍了如何替换多维数组中的键并保持顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出此数组:

$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))来用新键替换任意键一个",两个",三个",四个"或五个",而与深度无关那个钥匙.我需要该函数返回具有相同顺序结构的新数组.

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:

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

更改数组键而不更改顺序

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

这是我的尝试,不起作用:

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

致谢

推荐答案

此函数应将$oldKey的所有实例替换为$newKey.

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

这篇关于如何替换多维数组中的键并保持顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆