2016-02-04 43 views
1

鉴于此阵:如何更换多维数组键和维持秩序

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

问候

+0

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

回答

2

此功能应与$newKey取代的$oldKey所有实例。

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

这比我发现的其他方法非常清晰和简单。谢谢! –

+1

你必须通过“($ key === $ oldKey)”=> triple equale来更改“($ key == $ oldKey)”,因为当$ key equale = 0时它将被设置为“$ newKey”,而不是正确 –

+0

谢谢@AbdallahArffak。将来,请随时编辑答案,在编辑摘要中解释您的更改。如果它是有道理的,就像这样做,大多数人会很乐意接受编辑。 –