【问题标题】:How to replace key in multidimensional array and maintain order如何替换多维数组中的键并保持顺序
【发布时间】:2016-05-14 18:55:21
【问题描述】:

给定这个数组:

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

问候

【问题讨论】:

  • 您应该可以使用您链接的第二个问题中的方法。但是您需要制作一个搜索每个级别的递归版本。

标签: php arrays multidimensional-array replace key


【解决方案1】:

此函数应将所有$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;
}

【讨论】:

  • 你必须把 "($key == $oldKey)" 改成 "($key === $oldKey)" => 三等号,因为当 $key equale=0 时它会被设置"$newKey" 不正确
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
  • 2014-10-23
  • 1970-01-01
  • 1970-01-01
  • 2014-07-26
  • 1970-01-01
相关资源
最近更新 更多